# kōjō documentation > kōjō (工場) is an open-source, self-hosted software factory: autonomous agents that build features, fix bugs, review pull requests and audit security end to end, on request or on a schedule. It is one Go binary plus Postgres and runs in your own infrastructure with any model. Work is described by skills kept as files in a repository (.factory/skills//SKILL.md, goals.yaml, kit.yaml); a goal critic checks each result against goals.yaml before anything is published. Repository code runs only in sandboxes whose network egress goes through a proxy that holds the credentials, and changes are published as draft pull requests unless a merge policy says otherwise. It connects to GitHub, GitLab, Forgejo, Bitbucket, Slack, Mattermost, Discord, Microsoft Teams, a CLI and MCP. The entire kōjō documentation, concatenated for agent consumption. --- > Source: https://xavidop.github.io/kojo/docs # kōjō documentation kōjō (工場, "factory") is a software factory you run yourself. Its agents build features, fix bugs, review pull requests and audit security end to end, when someone asks or on a schedule. It is one Go binary plus Postgres. It runs in your infrastructure, with the model provider you choose. ## Start The [quick start](/docs/quickstart/) goes from nothing to a first session on one of your repositories: install the binary, start kōjō on one machine, connect GitHub, ask for a piece of work and read the draft pull request. [Install](/docs/install/) is the full reference, with Kubernetes, GitLab, Forgejo and Slack. To look at kōjō without an account or a model key, run the [local development stack](/docs/development/local-stacks/): a throwaway forge with a demo repository, and recorded model answers. ## What it does 1. A request arrives: a mention of the bot on an issue or pull request, a Slack message, `kojo run`, an MCP client, or a schedule. 2. kōjō decides whether the author may trigger work and whether that work may change code. 3. A session is queued in Postgres. A worker claims it and runs the orchestrator. 4. The orchestrator delegates to skills. Each skill runs as a subagent with its own tools, against a sandbox that holds a clone of the repository. 5. A goal critic checks each result against the skill's `goals.yaml`: commands that must pass, limits on the diff, and a rubric. A result that falls short goes back with the reasons. 6. If the work changed code, the merge policy decides how to publish it. The default is a draft pull request. [Concepts](/docs/concepts/) describes each step, the session states and the limits that apply. ## What makes it different | Property | How | |---|---| | It runs in your infrastructure | One binary, `kojo`, is the server, the egress proxy and the CLI. State is in Postgres. See [Deploy](/docs/deploy/). | | Any model | Skills name a tier, not a model. You map the tiers (`fast` and `strong` are required) to models of Anthropic, OpenAI, Google AI, OpenRouter or Ollama, or to an OpenAI-compatible gateway. See [Models](/docs/models/). | | Credentials stay out of the sandbox | The core holds the tokens and never runs repository code. Sandboxes run the code, see placeholders, and reach the network only through a proxy with an allowlist. The proxy sets a forge credential only on requests that read. See [Security](/docs/security/). | | "Done" is code | A skill is three files in `.factory/skills//`: instructions, acceptance criteria and sandbox requirements. See [Skills](/docs/skills/). | | Draft pull requests by default | Asking a human or merging low-risk changes are modes you opt into. See [Merge policy](/docs/merge-policy/). | | Sessions can be replayed and are costed | Model turns, tool calls, sandbox commands and critic verdicts are stored as steps, with tokens and cost. See [Observability](/docs/observability/). | | Changes without a redeploy | Models, budgets, policies, repositories, roles, schedules and skills are versioned config with rollback. See [Managing kōjō](/docs/manage/). | ## Where things are **Start** - [Quick start](/docs/quickstart/): from nothing to a first session on your repository. - [Install](/docs/install/): Compose on one VM, Helm, or the binary, then the first run. - [Concepts](/docs/concepts/): requests, sessions, the orchestrator, subagents, the goal critic, the trust boundary. **Skills** - [Skills](/docs/skills/): the `.factory/` layout and how skills resolve; the files [`SKILL.md`](/docs/skills/skill-md/), [`goals.yaml`](/docs/skills/goals/) and [`kit.yaml`](/docs/skills/kit/); [reference repositories](/docs/skills/reference-repositories/) and a [worked example](/docs/skills/example/). - [Built-in skills](/docs/built-in-skills/): the fourteen skills in the binary, for [changing code](/docs/built-in-skills/changing-code/), [reviews and audits](/docs/built-in-skills/reviews-and-audits/) and [scheduled upkeep](/docs/built-in-skills/scheduled-upkeep/). - [Schedules](/docs/schedules/): `schedules.yaml`, the cron syntax, schedules proposed in words. - [Evals](/docs/evals/): `kojo eval`, fixtures, evals from your own history, the activation gate. **Configure** - [kojo.yaml reference](/docs/config-reference/): every key of the deployment config, generated from the Go structs. - [Models](/docs/models/): tiers, providers, budgets, prices, the replay provider. - [Sandboxes](/docs/sandboxes/): choosing a driver by where sandboxes run: [sbx](/docs/sandboxes/sbx/) on one machine, [k8s](/docs/sandboxes/k8s/) on Kubernetes, [e2b](/docs/sandboxes/e2b/) at a sandbox service, [docker and fake](/docs/sandboxes/docker/) for development; and [kojo-proxy](/docs/sandboxes/proxy/), egress allowlists and credential injection. - [Surfaces](/docs/surfaces/): code platforms ([GitHub](/docs/surfaces/github/), [GitLab](/docs/surfaces/gitlab/), [Forgejo](/docs/surfaces/forgejo/)), chat platforms ([Slack](/docs/surfaces/slack/), [Mattermost](/docs/surfaces/mattermost/), [Discord](/docs/surfaces/discord/), [Microsoft Teams](/docs/surfaces/teams/)), issue trackers ([Linear](/docs/surfaces/linear/), [Jira](/docs/surfaces/jira/), [Asana](/docs/surfaces/asana/)), error tracking ([Sentry](/docs/surfaces/sentry/), [Datadog](/docs/surfaces/datadog/)) and tools (the CLI, MCP), and [who may trigger what](/docs/surfaces/triggers/). - [Merge policy](/docs/merge-policy/): the modes, the risk score, auto-merge, approvals. - [Products in several repositories](/docs/multi-repo/): linked repositories, changed together, one pull request each. - [Campaigns](/docs/campaigns/): one task across many repositories, a session each, at a bounded pace and cost, with a pilot first. - [Managing kōjō](/docs/manage/): what changes after the first deployment, roles, revisions and rollback. Then one page per tool: the [dashboard](/docs/manage/dashboard/) with screenshots, the [CLI](/docs/manage/cli/), [git](/docs/manage/git/), [MCP](/docs/manage/mcp/), the [HTTP API](/docs/manage/api/), and the [config objects](/docs/manage/objects/) key by key. **Operate** - [Deploy](/docs/deploy/): a [single VM with Compose](/docs/deploy/compose/) or [Kubernetes with Helm](/docs/deploy/helm/); several replicas, upgrades, secrets. - [CLI reference](/docs/cli/): every command and flag. - [Observability](/docs/observability/): traces, logs, session replay, cost; with [metrics](/docs/observability/metrics/) and the [audit log](/docs/observability/audit-log/). - [Security](/docs/security/): the model, its caveats, what `kojo doctor` checks. **Project** - [Development](/docs/development/): building, the repository, releases; with the [local stacks](/docs/development/local-stacks/) and [testing](/docs/development/testing/). - [Contributing](/docs/contributing/): how to propose a change. ## Schemas and machine-readable docs The JSON Schemas of the files kōjō reads are published with this site. `kojo schema` prints the same documents. | Schema | Describes | |---|---| | [kojo.schema.json](/schema/kojo.schema.json) | `kojo.yaml`, the deployment config | | [skill.schema.json](/schema/skill.schema.json) | The front matter of a `SKILL.md` | | [goals.schema.json](/schema/goals.schema.json) | `goals.yaml` | | [kit.schema.json](/schema/kit.schema.json) | `kit.yaml` | | [factory.schema.json](/schema/factory.schema.json) | `.factory/factory.yaml` | | [schedules.schema.json](/schema/schedules.schema.json) | `.factory/schedules.yaml` | | [config-export.schema.json](/schema/config-export.schema.json) | The file `kojo config export` writes | For coding agents, [llms.txt](/llms.txt) is an index of these pages and [llms-full.txt](/llms-full.txt) is all of them in one Markdown file. --- > Source: https://xavidop.github.io/kojo/docs/quickstart # Quick start This page takes you from nothing to a first session on one of your own repositories: kōjō on one machine, connected to GitHub, with a model you pay for. At the end you have a draft pull request that an agent wrote and that the goal critic checked. It is the short version of the single-machine install. [Install](/docs/install/) is the long one: every prerequisite, Kubernetes with Helm, GitLab, Forgejo and Slack. To look at kōjō without an account or a model key, use the [local development stack](/docs/development/local-stacks/) instead. It needs a checkout of the repository and runs on a throwaway forge with recorded model answers. ## What you need - **A machine with Docker and Docker Sandboxes.** macOS on Apple silicon, or Linux with KVM. Docker runs Postgres. Docker Sandboxes (`sbx`, 0.48.0 or newer) runs every session in its own microVM; [Docker's documentation](https://docs.docker.com/ai/sandboxes/install/) has the install steps. - **A model provider key.** The steps below use Anthropic. OpenAI, Google AI, OpenRouter, Ollama and OpenAI-compatible gateways are on the [Models](/docs/models/) page. - **A GitHub repository** you administer, with a protected default branch. kōjō refuses to enable a repository whose default branch is not protected. For GitLab, Forgejo or Bitbucket, follow [GitLab](/docs/surfaces/gitlab/), [Forgejo](/docs/surfaces/forgejo/) or [Bitbucket](/docs/surfaces/bitbucket/) at step 3. - **An address for kōjō**, such as `https://kojo.example.com`. GitHub delivers mentions in issues and pull requests to it as webhooks, and step 3 registers it with the GitHub App. Nothing has to answer there yet: `kojo run` needs no inbound connection, so everything on this page except the mention works before the address does. [Single VM with Compose](/docs/deploy/compose/#tls) shows a reverse proxy for it. ## 1. Install the binary ```sh curl -fsSL https://xavidop.github.io/kojo/install.sh | sh -s -- --compose-dir kojo cd kojo ``` The installer downloads the `kojo` binary of the latest release, checks its SHA-256, and installs it into `/usr/local/bin`, or into `~/.local/bin` when it cannot write there. With `--compose-dir kojo` it also puts the files of the single-machine install into the directory `kojo`: `docker-compose.yml` (Postgres), `kojo.yaml` and `.env.example`. It tells you when `sbx` or Docker is missing; it installs neither. ## 2. Configure it Secrets go into `.env`, which Docker Compose and kōjō both read: ```sh cp .env.example .env && chmod 600 .env ``` Set these in `.env`, as plain `NAME=value` lines without quotes: | Variable | Value | |---|---| | `POSTGRES_PASSWORD` | Letters and digits only. `openssl rand -hex 24` | | `KOJO_SESSION_SECRET` | `openssl rand -hex 32` | | `KOJO_ADMIN_TOKEN` | Your API token for the CLI, 16 characters or more. `openssl rand -hex 24` | | `ANTHROPIC_API_KEY` | The provider key. | | `KOJO_PUBLIC_URL` | The address GitHub and browsers reach kōjō at. | `kojo.yaml` is the deployment config. It holds no secret; it names them as `${VARIABLES}`. This is the file as it comes, without its comments, and it is enough to start: ```yaml server: public_url: "${KOJO_PUBLIC_URL}" listen: "127.0.0.1:8080" auth: session_secret: "${KOJO_SESSION_SECRET}" tokens: - name: admin token: "${KOJO_ADMIN_TOKEN}" role: admin database: url: "postgres://kojo:${POSTGRES_PASSWORD}@127.0.0.1:5432/kojo?sslmode=disable" models: gateway: embedded tiers: fast: provider: anthropic model: claude-haiku-5-5 strong: provider: anthropic model: claude-opus-5-5 budgets: per_session_usd: 10 per_day_usd: 200 sandbox: driver: sbx defaults: merge_policy: draft_only ``` Skills name a tier, `fast` or `strong`, and this file maps each tier to a model. The budgets stop a session at 10 USD and the whole install at 200 USD a day, but only for tiers that have a price: kōjō ships no price table, so add one as [Models](/docs/models/) describes. The [kojo.yaml reference](/docs/config-reference/) lists every key. ## 3. Create the GitHub App kōjō acts on GitHub as a GitHub App. One command registers it with the permissions and webhook events kōjō needs: ```sh kojo setup github --public-url https://kojo.example.com ``` Pass the address you set as `KOJO_PUBLIC_URL`: GitHub will deliver webhooks to `/webhooks/github` under it. Add `--org acme` to create the app in an organization instead of your account, and `--name` to call it something other than `kojo`: the name is what people mention, and app names are unique on GitHub. The command prints an address on your machine. Open it in a browser on the same machine and confirm the app on GitHub. The command then writes `secrets/github-app.pem` and `secrets/github-app.env`, and prints a `forges.github` block and the address where the app is installed on repositories. Three things are left to you: 1. Add the app's ID and webhook secret to `.env`: ```sh cat secrets/github-app.env >> .env ``` 2. In `kojo.yaml`, uncomment the `forges` block and set `private_key_file` to the path the command printed: ```yaml forges: github: app_id: "${GITHUB_APP_ID}" private_key_file: /home/you/kojo/secrets/github-app.pem webhook_secret: "${GITHUB_WEBHOOK_SECRET}" ``` 3. Install the app on the repository, at the address the command printed. The command needs no `kojo.yaml` and no running server. When the host has no browser, run it on your workstation and copy the `secrets` directory over. [Install](/docs/install/#create-the-github-app) lists the permissions the app asks for. ## 4. Start it Sign in to Docker Sandboxes and make deny-all its network policy. Both are needed once, as the user that runs kōjō: ```sh sbx login sbx policy init deny-all ``` Start Postgres, load `.env` into the shell, check the config and start kōjō: ```sh docker compose up -d set -a; . ./.env; set +a kojo config validate -f kojo.yaml kojo serve -f kojo.yaml ``` `kojo serve` applies the database migrations and stays in the foreground. Open a second terminal in the same directory for the rest of this page: ```sh set -a; . ./.env; set +a export KOJO_TOKEN="$KOJO_ADMIN_TOKEN" curl -fsS http://127.0.0.1:8080/readyz ``` The CLI talks to `http://localhost:8080` unless `KOJO_SERVER` says otherwise, and sends `KOJO_TOKEN` as its API token. ## 5. Enable a repository kōjō only works on repositories that are enabled. The list is empty on a new install. Write it to a file, `repos.yaml`, with your repository as `github/owner/name`: ```yaml version: 1 objects: - scope: org object: repos content: repos: github/acme/api: enabled: true ``` ```sh kojo config apply -i repos.yaml ``` Its last line is `1 of 1 object(s) applied`. When the default branch is not protected, it refuses and names the branch: protect it on GitHub and apply again. The file replaces the whole list, which is what a new install needs. [Install](/docs/install/#enable-a-repository) shows how to change a list that already has entries, and the other keys of an entry. ## 6. Run kojo doctor ```sh kojo doctor --remote ``` `kojo doctor` asks the running server to check itself: the database, the sandbox driver and its isolation, the GitHub App's permissions, branch protection, the model tiers and the budgets. It also starts a sandbox with an empty allowlist and has it try to reach the internet, which must fail. Each line is `ok`, `warn`, `FAIL` or `skip`. A `FAIL` makes the command exit 1: fix it before you go on. A new install has warnings, for example for a tier without a price and for sign-in without OIDC. [Install](/docs/install/#run-kojo-doctor) lists every check. ## 7. Ask for a first piece of work Pick something small in your repository: a missing flag, a small bug, an open pull request to review. ### From the CLI Say what you want in plain words. The orchestrator chooses the skills: ```sh kojo run --repo github/acme/api "add a --json flag to the export command, with a test" ``` `kojo run` prints the steps as they happen, then the summary, the goal critic's report and the pull request. Add `--dry-run` to see the diff without a branch or a pull request on GitHub. The same command starts other kinds of work. `--issue` and `--pr` say what the request is about, and `--skill` runs exactly one skill: ```sh kojo run --repo github/acme/api --issue 412 "fix this" kojo run --repo github/acme/api --pr 418 --skill review-pr kojo run --repo github/acme/api --skill security-audit --dry-run "audit the auth package" ``` ### From a mention Comment on an issue or a pull request and mention the app: ```text @kojo build this ``` `kojo` is the name of your GitHub App. The rest of the comment is the request: `@kojo fix this` on a bug report, `@kojo review this` on a pull request. The author of the comment needs write access to the repository, and GitHub must be able to reach kōjō's address. [Who may trigger what](/docs/surfaces/triggers/) has the rules. ## 8. Follow the session Every request becomes a session. List them, then read one by its ID, the `ses_...` value that `list` and `kojo run` print: ```sh kojo sessions list SESSION=ses_... kojo sessions logs "$SESSION" --follow kojo sessions show "$SESSION" ``` - `list` shows each session's status, repository, trigger, cost and title. - `logs` prints the steps: each skill, the files it read and edited, the commands that ran in the sandbox and the goal critic's verdict. `--follow` keeps printing until the session ends. - `show` prints the result: the summary, the goal critic's report with the outcome of each check, the risk, and the address of the pull request. Then open the pull request on GitHub. It is a draft from a `kojo/` branch onto the default branch, with one commit. Its description carries the summary, the goal critic's report and the risk. When the work fell short of its acceptance criteria, the pull request is still opened as a draft, and the description says what was not met. Nothing is merged: `draft_only` is the default [merge policy](/docs/merge-policy/). A session that changes no code opens no pull request. A review, for example, is one comment on the pull request it is about. [Local stacks](/docs/development/local-stacks/#a-first-session) has the output of these commands, captured from a session on the development stack. The dashboard shows the same sessions, with a replay of every step. It is served at kōjō's address, and signing in to it needs OIDC (`server.auth.oidc` in `kojo.yaml`), which this page does not set up. API tokens work for the CLI, the API and MCP, not in a browser. To stop, press Ctrl-C in the terminal of `kojo serve`, then run `docker compose down`. The database stays in its volume. ## Next steps - [Single VM with Compose](/docs/deploy/compose/): run kōjō as a systemd service, put TLS in front of it and back up Postgres. - [Install](/docs/install/): sign-in for the dashboard with OIDC, the Slack app, and Kubernetes with Helm. - [Built-in skills](/docs/built-in-skills/): the fourteen skills in the binary and what each one is held to. - [Skills](/docs/skills/): define what "done" means for your repository in `.factory/`. - [Automatic triggers](/docs/surfaces/triggers/#automatic-triggers-per-repository): run a skill on every new issue or pull request, without a mention. - [Merge policy](/docs/merge-policy/): ask a human in Slack, or merge low-risk changes. - [Concepts](/docs/concepts/): what happens between a request and a pull request. --- > Source: https://xavidop.github.io/kojo/docs/install # Install This page is the install reference: what kōjō needs, the three ways to install it, and the first-run steps in order. It is for whoever operates the install. - The [quick start](/docs/quickstart/) is the short version: one machine, GitHub, a first session, without the explanations. - [Deploy](/docs/deploy/) goes deeper into each path: TLS, backups, high availability, upgrades. - To build kōjō from source or run it without a forge account or a model key, see [Development](/docs/development/). ## Prerequisites ### Postgres Postgres is the only service kōjō depends on. The queue, the sessions, team memory, the audit log, the schedules and the runtime configuration live in it. - The compose install and the Helm chart both run `pgvector/pgvector:0.8.7-pg17`: Postgres 17 with the pgvector extension. The repository tests against that image. The code states no minimum Postgres version. - The `vector` extension (pgvector) is optional. The migrations run `CREATE EXTENSION IF NOT EXISTS vector`; when that fails, team memory uses Postgres full-text search only, and `kojo migrate` and `kojo doctor` say so. For embeddings, the database user must be allowed to create the extension, or it must exist already. - Configure the connection as `database.url` in `kojo.yaml`. ### A sandbox driver Every session runs repository code and model-written code in a sandbox. `sandbox.driver` in `kojo.yaml` selects how. | Driver | Where | Needs | |---|---|---| | `sbx` | one host | Docker Sandboxes (`sbx`) on the same host as kōjō, hardware virtualization, `sbx login` and `sbx policy init deny-all` | | `k8s` | Kubernetes | Kubernetes Agent Sandbox v1.0.12, a RuntimeClass that isolates (`kata` or `gvisor`), a CNI that enforces NetworkPolicy | | `e2b` | an E2B-compatible service (E2B Cloud, a self-hosted E2B, CubeSandbox) | an API key, a template, and a kojo-proxy the service's sandboxes can connect to. See [e2b](/docs/sandboxes/e2b/). | | `docker` | development | a Docker daemon, and `dev: true` in `kojo.yaml` | The `docker` driver starts plain containers and is for development only. [Sandboxes](/docs/sandboxes/) describes the drivers and the egress proxy. ### A sandbox image A skill's kit can name its image. The built-in skills name none, so their sandboxes start from `sandbox.image` in `kojo.yaml`, and from `ghcr.io/xavidop/kojo-toolchain:` when that is not set (`latest` for a development build). With the `e2b` driver an image is a template of the service, and the default is `sandbox.e2b.template`. The toolchain image is a Debian with git, make, a C compiler, Python, Node.js and Go, and a non-root user `agent`; its Dockerfile is [deploy/toolchain/Dockerfile](https://github.com/xavidop/kojo/blob/main/deploy/toolchain/Dockerfile). Each release publishes that image for linux/amd64 and linux/arm64 at its own version, so the default resolves without configuration. To use your own, set `sandbox.image`. `kojo doctor` creates a test sandbox from the same image, so it reports an image that cannot be pulled. ### A model provider `kojo.yaml` must define the model tiers `fast` and `strong`. With `models.gateway: embedded`, kōjō calls the provider itself and reads its key from the environment (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, `OPENROUTER_API_KEY`, `AZURE_OPENAI_API_KEY`); Vertex AI, Bedrock, and Azure without a key take the cloud's credentials instead; Ollama needs no key. `models.gateway` can instead be the URL of an OpenAI-compatible gateway. Set a budget (`models.budgets`): `kojo doctor` fails an install without a spend cap. kōjō ships no price table, so set a price per tier, or the budgets cannot bound that tier. See [Models](/docs/models/). ### A public URL and a sign-in method - `server.public_url` is how forges, Slack and browsers reach kōjō. Forges deliver webhooks to it, so they must be able to reach it. Slack in socket mode needs no inbound connection. - kōjō refuses to start without a sign-in method: OIDC (`server.auth.oidc`) or at least one API token (`server.auth.tokens`, 16 characters or more). API tokens work for the CLI, the API and MCP. Signing in to the dashboard in a browser needs OIDC. ## Ways to install | Path | Sandboxes | Use it when | |---|---|---| | [Docker Compose on one VM](#docker-compose-on-one-vm) | `sbx` | you have one host with hardware virtualization | | [Helm](#helm) | `k8s` | you run Kubernetes | | [The binary](#the-binary) | any, `e2b` included | you run the processes yourself, or only need the CLI | One version tag covers the binary, the image `ghcr.io/xavidop/kojo`, the sandbox toolchain image and the Helm chart. ## Docker Compose on one VM On one VM, Postgres runs in a container and kōjō runs on the host. The `sbx` CLI talks to the sandbox daemon of the host it runs on, and nothing supports driving it from inside a container, so `kojo serve` runs on the host, next to `sbx`. The compose file holds what does belong in a container: the database. ```mermaid flowchart LR forge["Forge: GitHub, GitLab, Forgejo or Bitbucket"] models["Model provider"] subgraph host["One host"] tls["TLS reverse proxy"] kojo["kojo serve"] pg[("Postgres, in Docker Compose")] vm["Docker Sandboxes: one microVM per session"] sproxy["Proxy of Docker Sandboxes"] end out["Allowlisted hosts"] forge -- "webhooks" --> tls --> kojo kojo -- "comments, commits, pull requests" --> forge kojo -- "model calls" --> models kojo --> pg kojo -- "sbx CLI" --> vm vm -- "all traffic" --> sproxy sproxy --> out ``` kōjō holds the forge credentials and the provider keys. It calls the model provider, and it makes the commits, comments and pull requests through the forge's API. A sandbox holds a clone of the repository and reaches the network only through the proxy of Docker Sandboxes, which lets through the hosts a skill's kit allows and sets the clone credential on requests to the forge. kojo-proxy is not used on this path. The install is the directory [deploy/compose](https://github.com/xavidop/kojo/blob/main/deploy/compose/docker-compose.yml) of the repository: | File | What it is | |---|---| | `docker-compose.yml` | One service, `postgres`: Postgres with pgvector, published on `127.0.0.1:5432`. | | `kojo.yaml` | The deployment config kōjō reads. It names secrets as `${VARIABLES}` and holds none. | | `.env.example` | Copy it to `.env` and fill it in. Docker Compose and the kōjō process both read it. | | `initdb/10-vector.sql` | Creates the `vector` extension when Postgres first initializes its data directory. | ### Get the binary and the files The installer downloads the binary and, with `--compose-dir`, these files of the same release, plus the systemd unit `kojo.service`: ```sh curl -fsSL https://xavidop.github.io/kojo/install.sh | sh -s -- --compose-dir kojo cd kojo cp .env.example .env && chmod 600 .env ``` Edit `.env`. Keep to plain `NAME=value` lines, without quotes: | Variable | Meaning | |---|---| | `POSTGRES_PASSWORD` | Password of the Postgres in the compose file. `kojo.yaml` puts it into the database URL: letters and digits only. | | `POSTGRES_PORT` | Loopback port Postgres is published on. Default `5432`. Change it in the database URL of `kojo.yaml` too. | | `KOJO_PUBLIC_URL` | `server.public_url`. | | `KOJO_SESSION_SECRET` | Signs the dashboard's session cookie. Generate it with `openssl rand -hex 32`. | | `KOJO_ADMIN_TOKEN` | The admin API token of `kojo.yaml`, for the CLI. At least 16 characters. | | `ANTHROPIC_API_KEY` | The key of the provider your tiers use. `OPENAI_API_KEY`, `GEMINI_API_KEY` and `OPENROUTER_API_KEY` work the same way. | Then edit `kojo.yaml`: the sign-in method, the forges, Slack and the model tiers. The blocks for OIDC, GitHub and Slack are commented out; a commented block does not ask for its variables. As shipped, kōjō binds `127.0.0.1:8080` and expects a TLS reverse proxy in front of it. ### Start it Prepare sbx once, as the user that will run kōjō: ```sh sbx login sbx policy init deny-all ``` Start Postgres, load `.env` into the shell, check the config, and start kōjō: ```sh docker compose up -d set -a; . ./.env; set +a kojo config validate -f kojo.yaml kojo serve -f kojo.yaml ``` `kojo serve` applies the database migrations when it starts and stays in the foreground. From a second terminal on the same host, with `.env` loaded: ```sh curl -fsS http://127.0.0.1:8080/readyz kojo doctor --remote --token "$KOJO_ADMIN_TOKEN" ``` To run kōjō as a service instead, use the systemd unit [deploy/systemd/kojo.service](https://github.com/xavidop/kojo/blob/main/deploy/systemd/kojo.service); its header lists the install commands. [Single VM with Compose](/docs/deploy/compose/) covers it, with TLS and backups. ## Helm The chart `charts/kojo` installs kōjō (`kojo serve`, two replicas by default), kojo-proxy (`kojo proxy`, two replicas by default), the RBAC of the `k8s` driver, the NetworkPolicy that locks sandbox pods down to the proxy, and by default a bundled Postgres with pgvector. It needs Kubernetes 1.25 or later. ```mermaid flowchart LR forge["Forge"] models["Model provider"] subgraph cluster["Kubernetes cluster"] ing["Ingress or HTTPRoute"] kojo["kojo serve, two replicas"] pg[("Postgres with pgvector")] asb["Agent Sandbox"] pods["Sandbox pods, on Kata or gVisor"] proxy["kojo-proxy, two replicas"] end out["Allowlisted hosts"] forge -- "webhooks" --> ing --> kojo kojo -- "comments, commits, pull requests" --> forge kojo -- "model calls" --> models kojo --> pg kojo -- "sandbox claims" --> asb --> pods kojo -- "allowlists and credentials" --> proxy pods -- "NetworkPolicy: the proxy only" --> proxy proxy --> out ``` The pieces are the same as on one VM, with two differences: sandboxes are pods that Kubernetes Agent Sandbox starts, and their only way out is kojo-proxy, which kōjō gives each session's allowlist and credentials. The cluster needs three things the chart does not install by default: 1. **Kubernetes Agent Sandbox v1.0.12.** Set `agentSandbox.install=true`, or install that release yourself. 2. **A RuntimeClass that isolates.** `sandbox.runtimeClassName` is `kata` by default; set it to `gvisor` on nodes that cannot run VMs. The chart installs no runtime. 3. **A CNI that enforces NetworkPolicy.** Without one the sandbox egress policy exists but does nothing. Install from the OCI registry, with the provider key in a Secret you create. `KOJO_VERSION` is a released version without the `v`: ```sh export KOJO_VERSION=X.Y.Z kubectl create namespace kojo kubectl -n kojo create secret generic kojo-env --from-literal=ANTHROPIC_API_KEY=... helm install kojo oci://ghcr.io/xavidop/charts/kojo --version "$KOJO_VERSION" -n kojo \ --set agentSandbox.install=true \ --set secrets.existingSecret=kojo-env ``` Or from the chart repository, which carries the same chart: ```sh helm repo add kojo https://xavidop.github.io/kojo helm repo update helm install kojo kojo/kojo -n kojo --create-namespace ``` Your part of `kojo.yaml` goes into the `config` value; secrets come from `secrets.existingSecret`. While `config` sets no sign-in method, the chart adds an admin API token named `bootstrap`: ```sh kubectl -n kojo get secret kojo-generated -o jsonpath='{.data.KOJO_BOOTSTRAP_TOKEN}' | base64 -d kubectl -n kojo port-forward svc/kojo 8080:8080 ``` [Kubernetes with Helm](/docs/deploy/helm/) has the values, the proxy, RBAC, the network policies and the database options. ## The binary `kojo` is one statically linked binary for Linux, macOS and Windows on amd64 and arm64. The same binary is the server, the egress proxy and the CLI. ### install.sh ```sh curl -fsSL https://xavidop.github.io/kojo/install.sh | sh ``` The script, for Linux and macOS: 1. Picks the release (the latest, or `--version`) and the archive for this OS and CPU: `kojo___.tar.gz`. 2. Downloads the archive and the release's `checksums.txt`, and stops unless the archive's SHA-256 is the one listed. 3. When `cosign` is installed, also verifies that `checksums.txt` was signed by the release workflow of `github.com/xavidop/kojo`. Without `cosign` it says that the signature was not checked. 4. Installs the binary into `/usr/local/bin`, with `sudo` when that needs it, or into `~/.local/bin` when it cannot write there. It runs `kojo version` to check that the binary starts. 5. With `--compose-dir DIR`, downloads the single-VM install of the same release into `DIR`: `docker-compose.yml`, `kojo.yaml`, `.env.example`, `initdb/10-vector.sql` and the systemd unit `kojo.service`. Files that exist are kept. It installs neither Docker nor Docker Sandboxes. It checks for `sbx`, `/dev/kvm` and `docker` and prints Docker's install instructions for what is missing. | Option | Environment variable | Default | Meaning | |---|---|---|---| | `--version vX.Y.Z` | `KOJO_VERSION` | the latest release | The release to install. | | `--dir DIR` | `KOJO_INSTALL_DIR` | `/usr/local/bin` | Where the binary goes. | | `--compose-dir DIR` | `KOJO_COMPOSE_DIR` | not set | Also fetch the compose install into `DIR`. | | `--base-url URL` | `KOJO_DOWNLOAD_URL` | the GitHub Release | A mirror of the release's files. | | `-h`, `--help` | | | Print the usage. | ```sh curl -fsSL https://xavidop.github.io/kojo/install.sh | sh -s -- --version vX.Y.Z --dir "$HOME/bin" ``` ### Other packages Each release also publishes, from [.goreleaser.yaml](https://github.com/xavidop/kojo/blob/main/.goreleaser.yaml): | Artifact | How to get it | |---|---| | Archives `kojo___.tar.gz` (`.zip` on Windows) | the GitHub Release; they hold the binary, the licences and the shell completions | | `.deb`, `.rpm` and `.apk` packages | the GitHub Release; there is no package repository, so download the file for your distribution | | Homebrew cask (macOS) | `brew install xavidop/tap/kojo` | | Scoop manifest (Windows) | `scoop bucket add xavidop https://github.com/xavidop/scoop-bucket`, then `scoop install kojo` | | Container image | `ghcr.io/xavidop/kojo:` and `latest`, for linux/amd64 and linux/arm64 | | Sandbox toolchain image | `ghcr.io/xavidop/kojo-toolchain:` and `latest`, for linux/amd64 and linux/arm64; built by the Release workflow, not by GoReleaser | `checksums.txt` is signed with Sigstore. To verify a download by hand: ```sh cosign verify-blob --certificate checksums.txt.pem --signature checksums.txt.sig \ --certificate-identity-regexp 'https://github.com/xavidop/kojo/' \ --certificate-oidc-issuer https://token.actions.githubusercontent.com checksums.txt sha256sum -c checksums.txt --ignore-missing ``` ## First run The steps below are the same for every install. Commands that read `kojo.yaml` need the variables it names: on one VM, load `.env` first (`set -a; . ./.env; set +a`); on Kubernetes, run them in the pod with `kubectl -n kojo exec deploy/kojo --`, where the file is `/etc/kojo/kojo.yaml`. ### Migrate the database `kojo serve` applies pending migrations when it starts, so a new install needs no separate step. Replicas that start together take turns on a Postgres advisory lock. To apply them yourself, before a rollout for example: ```sh kojo migrate -f kojo.yaml ``` It prints the number of migrations applied and exits. ### Create the GitHub App `kojo setup github` registers the GitHub App kōjō acts as, through GitHub's manifest flow. It needs no `kojo.yaml` and no running server, so you can run it on your workstation and copy the two files it writes. ```sh kojo setup github --public-url https://kojo.example.com --org acme ``` 1. The command serves a page on a loopback port and prints its address. It does not open a browser: open the address yourself, in a browser on the same machine. 2. The page sends the app's manifest to GitHub: the name (`kojo` unless you pass `--name`; app names are unique on a GitHub instance), the webhook URL `/webhooks/github`, the permissions and the events. 3. You review and confirm the app on GitHub. Without `--org` it is created in your user account. 4. GitHub redirects back to the command with a one-time code, which the command exchanges for the app's ID, private key and webhook secret. It waits up to 10 minutes. 5. It writes `github-app.pem` and `github-app.env` (`GITHUB_APP_ID`, `GITHUB_WEBHOOK_SECRET`) into the directory `secrets`, readable only by you, and prints their absolute paths, the `forges.github` block for `kojo.yaml` with the absolute path of the key, and the address where the app is installed on repositories. No secret is printed. `--out` names another directory. The app asks for these permissions: | Permission | Level | Used for | |---|---|---| | `metadata` | read | repositories, collaborators, rulesets | | `contents` | write | reading files, committing to `kojo/*` branches and to the branch of a person's pull request when they ask | | `issues` | write | reading issues, commenting | | `pull_requests` | write | opening, editing, commenting on and merging pull requests | | `checks`, `statuses` | read | the state of a commit | | `administration` | read | classic branch protection | Afterwards: 1. Add `GITHUB_APP_ID` and `GITHUB_WEBHOOK_SECRET` to the environment: `.env` on one VM, your Secret on Kubernetes. 2. Put the key where `forges.github.private_key_file` points, readable by the user kōjō runs as and by nobody else. The shipped `kojo.yaml` expects `/etc/kojo/secrets/github-app.pem`. 3. Uncomment the block in `kojo.yaml` and restart kōjō: ```yaml forges: github: app_id: "${GITHUB_APP_ID}" private_key_file: /etc/kojo/secrets/github-app.pem webhook_secret: "${GITHUB_WEBHOOK_SECRET}" ``` 4. Install the app on the repositories kōjō should work on, at the address the command printed. GitLab and Forgejo use an access token instead of an app, and Bitbucket Cloud the API token of a bot account; see [GitLab](/docs/surfaces/gitlab/), [Forgejo](/docs/surfaces/forgejo/) and [Bitbucket](/docs/surfaces/bitbucket/). None of them has an installation token, so the token kōjō hands the [proxy](/docs/sandboxes/proxy/#credential-injection) for clones is the configured one: it can write, and kojo-proxy sets it only on requests that cannot. ### Create the Slack app `kojo setup slack` prints the manifest of the Slack app. It creates nothing itself. ```sh kojo setup slack -o slack-manifest.yaml ``` 1. At `https://api.slack.com/apps`, choose Create New App, From a manifest, and paste the manifest. 2. Install the app to your workspace. 3. Put its tokens in the environment and add the block to `kojo.yaml`: ```yaml chat: slack: mode: socket bot_token: "${SLACK_BOT_TOKEN}" app_token: "${SLACK_APP_TOKEN}" ``` 4. Give the people who may approve pull requests and merges the `operator` role: approvals in Slack are checked against it. Socket mode, the default, needs no public ingress. For HTTP mode pass `--mode http --public-url https://kojo.example.com` and configure `signing_secret` instead of `app_token`. ### Enable a repository kōjō only works on repositories that are enabled. Webhooks from any other repository are answered and dropped, and `kojo run` is refused, a dry run included. Protect the default branch of a repository before you enable it. kōjō refuses to enable a repository whose default branch is not protected, in the dashboard and through `kojo config apply` alike, with a message that names the branch. Draft pull requests are a safeguard only where nothing can be pushed past them. `dev: true` skips this check. The list is the runtime config object `repos`. It starts empty. Each entry is a repository ID, `forge/owner/name`: | Key | Default | Meaning | |---|---|---| | `enabled` | `false` | The factory works on this repository. | | `skills` | all | Limit the repository to these skills. | | `auto` | none | Run a skill on a forge event without a mention: `issue_opened`, `pr_opened`, `pr_updated`, `check_failed`. Any other key is rejected. | | `allow_auto_merge` | `false` | Let the repository use the `auto_merge` policy. Only an admin sets it. | Change it in the dashboard under Settings, Repositories, or from the CLI with an admin token. Export the current state, edit the `repos` object, apply: ```sh export KOJO_SERVER=https://kojo.example.com export KOJO_TOKEN=... # an admin API token kojo config export -o kojo-state.yaml ``` The `repos` object in that file, with one repository enabled: ```yaml version: 1 objects: - scope: org object: repos content: repos: github/acme/api: enabled: true auto: pr_opened: review-pr ``` ```sh kojo config apply -i kojo-state.yaml --dry-run kojo config apply -i kojo-state.yaml ``` `apply` only touches the objects in the file, and each change is a new revision that can be rolled back. [Managing kōjō](/docs/manage/) covers the dashboard, revisions and roles. `kojo doctor` checks every enabled repository again: it fails one whose default branch is no longer protected, and one where kōjō cannot read user permissions. On Forgejo, Gitea and Bitbucket the bot account must be an admin of the repository for that; without it no mention can be authorized. ### Run kojo doctor `kojo doctor` checks the install and exits 1 when a check fails. Run it after every change to the install. When the server runs on the same host, ask it: ```sh kojo doctor --remote --token "$KOJO_ADMIN_TOKEN" ``` Without `--remote`, `kojo doctor -f kojo.yaml` builds the checks from the local config in its own process. On Kubernetes that is how the chart's notes run it, inside the pod. The dashboard's **Doctor** page, under Records, runs the same checks on the server for anyone with the `operator` role.
The Doctor page of the dashboard: a banner saying one check failed, and a table of three checks marked ok, failed and warning, each with a detail.
The report of the demo server: its fake sandbox driver fails the isolation check and its made-up prices give a warning.
Each line is a status (`ok`, `warn`, `FAIL` or `skip`), the name of the check and a detail. The last line counts them. These are the checks and what each prints when it passes: | Check | Passes with | |---|---| | `mode` | `production mode`. It fails while `dev: true` is set. | | `database` | `reachable, migrations applied` | | `team memory` | `pgvector is available`. Without pgvector it is a warning. | | `sandbox driver` | the driver, its version and a detail | | `sandbox isolation` | the isolation level. A driver that shares the host's kernel fails. | | `sandbox egress` | `sandboxes have no route out except the proxy` | | `egress probe` | `a sandbox with an empty allowlist could not reach example.com, through the proxy or around it` | | `kojo-proxy` | `N replicas; this server remembers M sandbox policies`, when the proxy is remote. One replica is a warning. | | `kojo-proxy
` | `instance , ready, holds N sandbox policies, all M of this server's among them`, one line per replica of a remote proxy. A replica that does not answer, signs with another CA than the others, answers for several replicas behind one address, or is ready but lacks policies or deletes of this server fails. One that is not ready yet is a warning: it takes no sandbox traffic. Only the running server remembers policies, so ask it (`--remote`, or the dashboard) to compare them; a local `kojo doctor` remembers none. | | `forge ` | `reachable, permissions sufficient` | | `trigger permissions ` | `user permissions are readable` | | `branch protection ` | the default branch is protected, with its required checks and reviews | | `skill activation` | `an eval at N% is required`. Without a required eval it is a warning. | | `budgets` | `per session $X, per day $Y, per month $Z`. No per-session or per-day cap fails (a monthly cap alone does not bound a runaway day); a tier without a price is a warning. | | `model provider ` | where the credentials came from, and ` answers`. One line per provider a tier, a fallback or the embedder uses. | | `model tier ` | `/ answers` | | `chat ` | `tokens work` | | `dashboard sign-in` | `OIDC with `. API tokens without OIDC are a warning. | | `session reports` | `links are signed with a key derived from server.auth.session_secret`. Without a session secret it is a warning: no link to a [shareable report](/docs/observability/reports/) is made. | Other lines appear only when something is off: `sandbox docker` (sandboxes cannot run their own Docker daemon), `repositories` (none is enabled yet), `forges` (none is configured), `dashboard admins` (nobody has the admin role), `public URL` (not https) and `network policies` (the Helm chart's NetworkPolicies are off). The egress probe creates a real sandbox with an empty allowlist and tries to reach `example.com` through the proxy and around it. `--skip-probe` leaves it out. A run without failures ends like this and exits 0. Warnings do not change the exit code: ```text 12 ok, 2 warning(s), 0 failed, 0 skipped ``` A first install usually has warnings: `skill activation` until an eval is required, `budgets` until every tier has a price, and `dashboard sign-in` until OIDC is configured. ### Verify with a first session Start a session from the CLI on an enabled repository, with a token that has the `operator` role or more: ```sh export KOJO_SERVER=https://kojo.example.com export KOJO_TOKEN=... kojo run --repo github/acme/api --issue 412 "fix this" ``` `kojo run` prints the session's steps as they happen, then the summary, the goal critic's report and the pull request. Code changes come back as a draft pull request unless the repository's [merge policy](/docs/merge-policy/) says otherwise. `--dry-run` does the work and pushes nothing. A mention does the same from the forge: `@kojo fix this` in a comment on an issue, where `kojo` is the name of your GitHub App or the login of the bot account. That path also proves that webhooks arrive. The quick start walks through [asking for work](/docs/quickstart/#7-ask-for-a-first-piece-of-work), with more kinds of requests, and [following the session](/docs/quickstart/#8-follow-the-session) to the pull request. ## Next steps - [Deploy](/docs/deploy/): TLS, backups, high availability, upgrades and secrets. - [Skills](/docs/skills/): what the factory can do and how to change it. - [Merge policy](/docs/merge-policy/): drafts, approvals and auto-merge. - [CLI reference](/docs/cli/): every command and flag. --- > Source: https://xavidop.github.io/kojo/docs/concepts # Concepts This page describes the model of kōjō as it is built: how a request becomes a session, what runs inside a session, and what limits apply. Read it before you write skills or change policies.
A factory line with five stations: a parcel enters at an intake hopper, a robot arm works on it inside a glass booth, it passes an orange inspection gate, then a control desk, and leaves sealed. A factory line with five stations: a parcel enters at an intake hopper, a robot arm works on it inside a glass booth, it passes an orange inspection gate, then a control desk, and leaves sealed.
The factory in one picture: a request comes in, a skill works on it inside a sandbox, the goal critic inspects the result, the merge policy decides how it is published, and a draft pull request leaves. The illustration was generated with Gemini.
## The pipeline Every piece of work follows the same path: 1. A **request** arrives on a surface: a forge webhook, a Slack message, the CLI, the dashboard, an MCP client or a schedule. 2. **Intake** decides whether kōjō acts on it and whether it may change code. 3. The request is stored and a **session** is queued in Postgres. 4. A worker claims the session and runs the **orchestrator**, or one skill directly when the request names it. 5. The orchestrator delegates to **subagents**. Each subagent is one skill, with that skill's tools, running against a sandbox. 6. The **goal critic** checks each subagent's result against the skill's acceptance criteria and sends it back with feedback when it falls short. 7. If the workspace changed, the **merge policy** decides how the change is published. The default is a draft pull request. 8. The result is delivered where the request came from: a comment, a thread reply, or the session record that the CLI, the dashboard and MCP read. The parts that take part, and what each one talks to, for a session the orchestrator runs: ```mermaid flowchart TD S["Surfaces: forge webhook, Slack, CLI, dashboard, MCP, schedule"] subgraph core["kōjō core"] I["Intake"] O["Orchestrator"] -- delegate --> A["Subagent: one skill"] A -- "final report" --> C["Goal critic"] C -- "rejected: feedback" --> A C -- verdict --> O O -- "work done" --> M["Merge policy"] G["Model gateway"] end S --> I I -- "request stored, session queued" --> Q[("Postgres")] Q -- "a worker claims the session" --> O O -. "model calls" .-> G A -.-> G C -.-> G A -- "tools: exec, copy" --> X["Sandbox, through the driver"] C -- checks --> X X -- egress --> P["Proxy: allowlist, credentials"] M -- "branch, commit, pull request" --> F["Forge API"] ``` ## Requests and intake Every surface normalizes into one request: who asked (the actor), on which surface, about which repository and issue or pull request, and the text. A request also carries a `trusted` flag for its actor. Intake sets it; nothing later can raise it. | Source | Becomes work when | Trusted (may change code) when | |---|---|---| | Forge mention of the bot account | The author has the repository's `trigger_permission` (default `write`). Otherwise the request is rejected and audited. | Always, once accepted | | Forge event: issue opened, pull request opened or updated, check failed | An operator configured a skill for that event in the repository's `auto` map. Otherwise it is ignored. | The event's author has `trigger_permission` | | Forge push to the default branch | Never a session: it re-reads the repository's `.factory/` files | Not applicable | | Slack direct message or mention | Always | The sender's email has the `operator` or `admin` role in kōjō | | `kojo run`, the dashboard, MCP | The caller has the `operator` role (the API requires it) | Always | | Schedule | The schedule is enabled and due | Always | A mention or a chat message that would become work does not start a second session when a session is already at work on the same issue, pull request or chat thread: it goes to that session as a message its next model step reads. See [Talking to a session at work](/docs/surfaces/triggers/#talking-to-a-session-at-work). Further rules that intake applies: - A request for a repository that is not enabled is rejected. That includes dry runs: a skill test cannot read a repository kōjō was not enabled on. - A forge delivery is enqueued once. The delivery ID is the deduplication key. - A skill draft can only run in a dry-run request. - A chat message names its repository as `forge/owner/name`. Without one, the request uses the only enabled repository, if there is exactly one. A request from an untrusted actor is handled read-only: it only reaches skills that cannot change the workspace, it never publishes a change, and it cannot save [team memory](/docs/memory/). See [Security](/docs/security/) for the full list, and [Surfaces](/docs/surfaces/) for how each surface is connected. ## Sessions A session is one request being handled. It is also the queue entry: workers claim sessions from Postgres with `FOR UPDATE SKIP LOCKED`, so there is no separate queue. ### States | Status | Meaning | |---|---| | `queued` | Waiting for a worker, or waiting for its next look at something (a retry, the merge wait, a spent daily budget) | | `running` | Claimed by a worker, which holds a lease on it | | `waiting` | Parked until a human decides an approval, or until the approval's deadline passes | | `succeeded` | Finished, and the goal critic accepted every delegated skill | | `failed` | Finished with an error, or delivered with a report that the work fell short | | `cancelled` | Stopped on request | A session moves between them like this: ```mermaid stateDiagram-v2 [*] --> queued: request accepted queued --> running: a worker claims it running --> queued: retry, merge wait, spent daily budget, shutdown running --> waiting: approval asked waiting --> queued: approval decided waiting --> running: approval deadline passed running --> succeeded running --> failed running --> cancelled: cancel requested queued --> cancelled: cancel requested waiting --> cancelled: cancel requested succeeded --> [*] failed --> [*] cancelled --> [*] ``` A session also has a phase that is stored in its checkpoint: | Phase | What happens in it | |---|---| | `work` | The orchestrator or the named skill runs, then the result is finalized | | `plan` | Before a skill that changes code, the session posted a [plan](/docs/plan-first/) and waits for the go-ahead, writes a revised plan, or ends without changing anything when the plan is declined or nobody answers by the deadline | | `approval` | The session waits for an approval decision, then acts on it. Without a decision by the deadline it opens a draft pull request, leaves its pull request unmerged, or, in a follow-up, pushes only to a draft: see [No answer](/docs/merge-policy/#no-answer). | | `merge_wait` | The session looks at the pull request's checks once a minute and merges when they are green | ### Outcomes The session result records one outcome: | Outcome | Meaning | |---|---| | `draft_pr_opened` | A draft pull request was opened | | `pr_opened` | A pull request ready for review was opened | | `merged` | The pull request was merged after its checks passed | | `answered` | Nothing to publish; the answer was posted where the request came from | | `no_change` | No skill ran and there was nothing to say | | `dry_run` | A dry run: the diff is kept in the result, nothing was pushed or posted | | `declined` | A human declined to open the pull request, or, in a follow-up, to push to it; or the policy asked for a person and nobody could be asked about a pull request ready for review | | `pushed` | A [follow-up](/docs/surfaces/triggers/#follow-ups) added a commit to the pull request kōjō opened | | `branch_moved` | A follow-up pushed nothing: someone pushed to the pull request's branch while it worked | | `round_limit` | A follow-up did nothing: the pull request had used all its rounds | | `plan_declined` | A person declined the [plan](/docs/plan-first/), or asked for more revisions than allowed: nothing was changed | | `plan_expired` | Nobody answered the plan before its deadline: nothing was changed | | `failed_with_report` | The work did not meet its acceptance criteria and was delivered with the report. In a follow-up on a pull request ready for review, nothing was pushed and the report was posted. | | `failed` | The session ended with an error before it produced a result | ### Workers, leases and resume `kojo serve` runs `server.workers` workers per replica (default 4). A worker polls the queue every 2 seconds and is woken at once when a request is enqueued. - A claim holds a lease of 2 minutes. The worker renews it every 30 seconds. - If a worker dies, its lease expires and another worker claims the session. - If a worker loses its lease to another worker, it stops and touches nothing. - On shutdown the session is checkpointed and put back in the queue. Another replica, or the same one after the restart, resumes it. ### Checkpoints The checkpoint is a JSON document on the session row. It holds the phase, the orchestrator's conversation, the results of the delegated skills, the values they recorded, the sandboxes the session owns, the base commit, the pull request it opened and the approval it waits on. The checkpoint is saved after every orchestrator turn and after every delegated skill. A resumed session continues from the last complete orchestrator turn. A subagent's own conversation is not checkpointed: a skill run that was interrupted starts again from its first turn, in the same sandbox, so it sees the workspace as the interrupted run left it. A session pins its configuration. It records the config revision IDs and the skill versions it started with, and a resumed session uses those revisions even if the dashboard changed them meanwhile. See [Managing kōjō](/docs/manage/). ### Retries There are three kinds, at three levels: | Level | What is retried | Limit | |---|---|---| | Goal critic | A rejected result goes back to the same subagent with the critic's feedback | The skill's `max_attempts` (default 3) | | Rubric judge | A judge answer that carries no verdict is asked for again | One retry; then the skill run ends with an error | | Session | A transient failure puts the session back in the queue, 30 seconds later the first time and 60 seconds later the second | At most 2 retries per session, counted in its checkpoint. Dry runs are never retried. | Failures that are not retried: any failure of a dry run (a skill test or an eval), a budget that is reached, a sandbox driver that is unavailable, a missing recording of the replay model provider, and errors kōjō marks as permanent (an unknown skill, a forge that is not configured, a change too large to publish). A session that fails tells whoever asked, with the error and a link to the session. A session gets its terminal status last. Its sandboxes are destroyed and `session.end` is written to the audit log before the status changes, so a client that waits for a terminal status finds nothing still in flight. ### Budgets and limits kōjō enforces spend in USD. It does not enforce a token cap; tokens are counted and shown per session and per step. | Limit | Default | Where it is set | |---|---|---| | Spend per session | From `kojo.yaml` at first start | `budgets.per_session_usd` in the models settings | | Spend per day (rolling 24 hours, every session of the install, evals included) | From `kojo.yaml` at first start | `budgets.per_day_usd` in the models settings | | Orchestrator turns per session | 30 | Fixed | | Model turns per attempt of a skill run | 40 | `max_steps` in `SKILL.md` | | Critic attempts per skill run | 3 | `max_attempts` in `goals.yaml` | | One `exec` tool call | 600 s, at most 3600 s | `timeout_seconds` argument | | One goal check | 10 min | `timeout` on the check | | Sandbox lifetime | 4 h | `sandbox.ttl` in `kojo.yaml` | | Wait for green checks before a merge | 120 looks, one a minute | Fixed | | Interim replies per session | 5 | Fixed | | Comments per skill run | 3 | Fixed | | Files published by one session | 500 files, 1 MiB each, 16 MiB together | Fixed | Both budgets are checked before every model call. A running session that reaches a budget or a turn limit stops working, and what exists is still delivered with a report. A session that has not started yet waits while the daily budget is spent: it is put back in the queue for 10 minutes at a time, instead of starting and failing at its first model call. A value of 0 disables that budget. kōjō ships no model price table. A tier without a configured price costs 0, so the USD budgets do not bound it. See [Models](/docs/models/). ### Cancellation Cancel a session with `kojo sessions cancel`, from the session page of the dashboard, or with `POST /api/v1/sessions/{id}/cancel`. - A `queued` or `waiting` session is cancelled at once. - A `running` session is flagged. Its worker sees the flag at the next heartbeat (within 30 seconds), stops, destroys the session's sandboxes and records `session.cancel` in the audit log. Cancelling is always this explicit action. A message to a session at work never cancels it, whatever its words. ## The orchestrator Each session without a named skill runs one orchestrating agent on the `strong` model tier. There is no workflow graph: the orchestrator reads the request and decides which skills to run and in which order. The orchestrator has no shell and no file access. Its tools are: | Tool | What it does | Available when | |---|---|---| | `delegate` | Runs one skill as a subagent and returns the critic's verdict, the report, the recorded values and the changed files | Always | | `memory_search` | Searches [memory](/docs/memory/): the team's for the repository, and the personal memory of whoever asked | Always | | `memory_save` | Saves a preference to the personal memory of whoever asked | The request was made by a person (a mention, a chat message, a manual run, a campaign) and is not a dry run | | `reply` | Posts a short interim message to whoever asked | The request has a thread, issue or pull request to answer in, and is not a dry run | | `propose_schedule` | Proposes a recurring job, shown in chat for confirmation | The request came from chat and its actor is trusted | The orchestrator's last answer without a tool call is the session's summary. When the request names a skill (a schedule, an automatic forge event, `kojo run --skill`), the orchestrator is skipped and that skill runs once. ## Subagents and tools A subagent is one run of one skill. It starts with a fresh context: the skill's instructions, a description of its environment, the repository's `AGENTS.md` and `.factory/memory` knowledge, what kōjō [remembers](/docs/memory/) (the asker's own preferences, the lessons maintainers taught the skill in reviews, matching team memory), and the task the orchestrator wrote. It does not see the orchestrator's conversation. A subagent has exactly the tools its skill lists, and in a [follow-up](/docs/surfaces/triggers/#follow-ups) on one of kōjō's pull requests the two that read that pull request's review and checks. The limit is enforced when a tool call is dispatched, not only in what the model is shown. | Tool | What it does | Runs in the sandbox | Changes the workspace | |---|---|---|---| | `read_file` | Reads a file, optionally a line range | Yes | No | | `list_files` | Lists files under a directory, optionally by glob | Yes | No | | `search` | Searches the workspace for a regular expression | Yes | No | | `write_file` | Creates or overwrites a file | Yes | Yes | | `edit_file` | Replaces one exact occurrence of a string | Yes | Yes | | `exec` | Runs a shell command | Yes | Yes | | `git_diff` | Shows the changes made so far | Yes | No | | `set_output` | Records a named value for later skills and for the goal checks | No | No | | `memory_search` | Searches team memory and the asker's personal memory | No | No | | `memory_save` | Saves a fact to team memory, or a preference to the asker's personal memory | No | No | | `get_issue` | Reads an issue and its comments | No | No | | `list_issues` | Lists the repository's issues | No | No | | `list_pull_requests` | Lists the repository's pull requests: open, closed, merged or all | No | No | | `get_pr` | Reads a pull request | No | No | | `get_pr_diff` | Reads the diff of a pull request | No | No | | `comment` | Posts a comment on the issue or pull request the session is about | No | No | | `get_review_comments` | Reads the review of a pull request: comments on lines and the text of each review | No | No | | `get_check_runs` | Reads the checks of a commit, with their output where the forge keeps it | No | No | The tools that read the forge, and `comment`, go through the core's own forge client. The sandbox is not involved. A skill "writes" when it lists a tool that changes the workspace and does not set `constraints.no_changes`. Untrusted requests cannot reach such skills. Skills, their files and their layering are described in [Skills](/docs/skills/). ### Sandboxes and the workspace A skill that uses a sandbox tool, or that has goal checks, gets a sandbox. A session has one sandbox per image. The first one clones the repository at the default branch, or at the pull request's head when the session is about a pull request. When a later skill needs another image, the workspace is copied into the new sandbox. Before every skill run the sandbox's policy is applied again: the egress allowlist is narrowed to that skill's kit and short-lived credentials are refreshed. A kit's `setup` commands run once per skill and session, each recorded as a step. When the session ends, its sandboxes are destroyed. See [Sandboxes](/docs/sandboxes/). ## The goal critic The critic judges what one skill run changed, measured from the workspace as it was when that run started. It applies the skill's acceptance criteria in this order: 1. Every value in the skill's `outputs` was recorded with `set_output`, and there is a final report. 2. The constraints on the diff: `no_changes`, `max_changed_lines`, `forbidden_paths`, `required_paths`. 3. The checks: commands that run in the sandbox and must exit 0. A check with `expect_failure` must exit non-zero. A check with `skip_if_unset` is skipped when a value it names was not recorded. A check that times out never passes. 4. The rubric judge, when the skill has one. It runs only if everything above passed, so no model call is spent on work that already failed. It grades the task, the report and the diff, and answers with a pass or the unmet rubric items. A rejected result returns to the same subagent with the unmet criteria and the output of the failed checks. After the last attempt the result is kept either way: failed work is reported, never dropped. The schema of `goals.yaml` is on the [goals.yaml](/docs/skills/goals/) page. ## Merge policy and publishing When the session's work is done, kōjō diffs the workspace against the base commit. - No change, a request without a repository, or an untrusted actor: the summary is posted as an answer. - A dry run: the diff is stored in the session result and nothing is pushed or posted. - Otherwise the merge policy scores the change and chooses an action. Under the default mode, `draft_only`, that is always a draft pull request. The core publishes. It reads the changed files out of the sandbox, creates a `kojo/-` branch through the forge API, commits the files and opens the pull request. The sandbox never pushes. The modes, the risk score and auto-merge are described in [Merge policy](/docs/merge-policy/). ## The trust boundary kōjō has two sides, and the line between them is the main security property. ```mermaid flowchart TD subgraph trusted["kōjō core: holds every credential"] C["Decides what runs, never runs repository code"] end subgraph untrusted["Sandbox: sees placeholders only"] W["Shell, git, toolchains: runs repository and model-written code"] end C -- "exec and copy, through the driver" --> W W -- "output, files, diffs" --> C C -- "allowlist and credentials" --> P["Proxy, outside the sandbox"] W -- "all egress" --> P P -- "credential set on the way out" --> H["Hosts on the skill's allowlist"] C -- "push, comment, merge" --> F["Forge API"] ``` - The core holds every credential. It never runs a repository command and never shells out to git. - The sandbox runs everything that is untrusted. It holds placeholders; a proxy outside the sandbox sets the real credential on requests to allowlisted hosts. kojo-proxy sets a forge's clone credential only on git's fetch. - What the core reads back from a sandbox is bounded in size and count. [Security](/docs/security/) covers the boundary in detail, with its known limits. ## Lifecycle of a bug report A maintainer comments on issue 123 and mentions the bot. The repository uses the default merge policy. ```mermaid sequenceDiagram participant F as GitHub participant C as Core participant O as Orchestrator participant S as Subagent participant G as Goal critic participant X as Sandbox F->>C: webhook, a mention on issue 123 Note over C: Signature verified. Intake checks the repository, the author's permission and the delivery ID Note over C: Session queued, then claimed by a worker. Config revisions pinned, skills resolved C->>O: run on the strong tier O->>S: delegate reproduce-bug C->>X: create, fetch the repository S->>X: write a failing test S->>G: final report G->>X: run the checks G-->>O: accepted, checks and rubric passed O->>S: delegate fix-bug S->>X: edit, run tests S->>G: final report G->>X: run the checks G-->>S: rejected, with feedback S->>X: edit again S->>G: final report G->>X: run the checks G-->>O: accepted on attempt 2 O-->>C: final answer, the summary Note over C: Diff since the base commit, risk score, merge policy draft_only C->>X: read the changed files C->>F: branch kojo/slug-id, commit, draft pull request C->>F: comment on issue 123 with the summary and the link C->>X: destroy Note over C: Status succeeded, outcome draft_pr_opened ``` If the critic had rejected the fix on its last attempt, the change would still be published as a draft, with the critic's report in the pull request body, and the session would end as `failed` with the outcome `failed_with_report`. ## Glossary | Term | Meaning | |---|---| | Request | The normalized form of something asked of kōjō: actor, surface, repository, issue or pull request, text | | Actor | Who asked. `trusted` when they may trigger write actions | | Surface | Where requests come from and answers go: `github`, `gitlab`, `forgejo`, `bitbucket`, `slack`, `cli`, `mcp`, `dashboard`, `schedule` | | Intake | The code that accepts or rejects a request and sets its trust | | Session | One request being handled; also the queue entry a worker claims | | Phase | Where a session is in its life: `work`, `approval` or `merge_wait` | | Checkpoint | The session's saved state, from which another worker can resume it | | Lease | A worker's time-limited claim on a session (2 minutes, renewed by heartbeat) | | Orchestrator | The agent that decides which skills to run. It has no shell and no file access | | Skill | A role defined as files: instructions, tools, model tier, acceptance criteria and a sandbox kit | | Subagent | One run of one skill, with a fresh context | | Tool | An action a subagent may take. A skill lists the tools it has | | Output | A named value a subagent records with `set_output`; later skills and goal checks read it | | Kit | The sandbox part of a skill: image, resources, egress allowlist, credential names | | Sandbox | The isolated environment that holds the workspace and runs untrusted code | | Workspace | The repository checkout inside the sandbox, at `/workspace` | | Goal critic | The check of a subagent's result against its skill's acceptance criteria | | Check | A command that must exit 0 (or non-zero with `expect_failure`) for the critic to accept | | Judge | The model that grades a result against the skill's rubric, after the deterministic criteria passed | | Merge policy | The rules that decide how a change is published: draft, ask, or merge | | Risk score | A number from 0 to 1 that the merge policy computes for a change; it maps to low, medium or high | | Approval | A question put to a human in chat with Approve and Deny buttons | | Step | One recorded action of a session: a model turn, a tool call, a sandbox command, a critic verdict. Steps are what session replay shows | | Team memory | Facts about a repository or the org, stored in Postgres and searched by subagents. See [Memory](/docs/memory/) | | Personal memory | What one person asked kōjō to remember; read only in sessions that person starts | | Lesson | A team memory learned from a maintainer's review of a pull request kōjō opened | | Config revision | One version of one runtime config object. Sessions pin the revisions they start with | | Tier | A named model slot (`fast`, `strong`) that the models settings map to a concrete model | | Dry run | A session that pushes and posts nothing: skill tests and evals | --- > Source: https://xavidop.github.io/kojo/docs/skills # Skills A skill is a role for a subagent: its instructions and tool limits (`SKILL.md`), what "done" means (`goals.yaml`) and the sandbox it runs in (`kit.yaml`). This page covers where kōjō finds skills and how it layers them, a repository's `factory.yaml`, how to list and validate skills, and what makes a good one. Read it before you write or override a skill.
A workbench with a sheet of instructions, a measuring gauge with an orange dial, and an open toolbox. A workbench with a sheet of instructions, a measuring gauge with an orange dial, and an open toolbox.
A skill brings three things to the bench: its instructions (SKILL.md), the gauge its work is measured with (goals.yaml), and the tools of its sandbox (kit.yaml).
Each file, and what goes with it, has its own reference page: - [SKILL.md](/docs/skills/skill-md/): the front matter and the instructions, the tool catalog, skill outputs, and the `AGENTS.md` and `.factory/memory/` text every subagent receives. - [goals.yaml](/docs/skills/goals/): checks and the values they read, constraints on the diff, the judge, and how the goal critic applies them. - [kit.yaml](/docs/skills/kit/): the sandbox's image, resources, egress allowlist, credentials and setup commands. - [Reference repositories](/docs/skills/reference-repositories/): other repositories a request names for the skills to read next to the session's own. - [Worked example: fix-bug](/docs/skills/example/): the three files of a built-in skill and how they work together. - [Skills CI](/docs/skills/ci/): a GitHub Action that validates and evaluates the skills a pull request changes, and reports on the pull request. ## The .factory directory kōjō reads a repository's factory-as-code from `.factory/` at the head of the default branch, through the forge API. It never reads these files from a pull request's head or from the sandbox, so a change to `.factory/` only takes effect once it is on the default branch. ### In a repository ```text AGENTS.md # optional, at the repository root .factory/ ├── factory.yaml # optional: this repository's merge policy ├── schedules.yaml # optional: recurring jobs for this repository ├── skills/ │ └── fix-bug/ # one directory per skill; its name is the skill's name │ ├── SKILL.md # required: front matter and instructions │ ├── goals.yaml # optional: acceptance criteria │ └── kit.yaml # optional: the sandbox └── memory/ # optional: notes handed to every subagent └── testing.md ``` | Path | Read as | |---|---| | `.factory/skills//SKILL.md` | A skill. A directory without `SKILL.md` is ignored. | | `.factory/skills//goals.yaml` | The skill's [goals](/docs/skills/goals/). | | `.factory/skills//kit.yaml` | The skill's [kit](/docs/skills/kit/), unless the front matter's `kit:` names another file. | | `.factory/factory.yaml` | [Repository settings](#factoryyaml). | | `.factory/schedules.yaml` | Recurring jobs. See [Schedules](/docs/schedules/). | | `.factory/memory/**` | [Repository knowledge](/docs/skills/skill-md/#agentsmd-and-factorymemory). | | `AGENTS.md` | The repository's own instructions for agents. | The result is cached by commit: when the default branch has not moved, resolving a repository's skills costs one forge API call. A repository can also keep eval cases for its skills under `.factory/evals///`, and recorded model answers for them. The server does not read them; `kojo eval --local --factory .factory` and the [Skills CI](/docs/skills/ci/) action do. ### In an org-level repository Org-level skills can live in one shared repository instead of the dashboard. That repository uses the same layout: `.factory/skills//` on its default branch. For the org layer kōjō takes only the skills from it; its `AGENTS.md`, `factory.yaml`, `schedules.yaml` and `memory/` do not apply to other repositories. Where each scope's skills are edited is the `settings/skills_source` config object: | Field | Values | Seeded from `kojo.yaml` | Default | |---|---|---|---| | `org` | `dashboard` or `git` | `seed.skills_source.org` | `dashboard` | | `repo` | `dashboard` or `git` | `seed.skills_source.repo` | `git` | | `skills_repo` | `forge/owner/name` | `defaults.skills_repo` | none; required when `org` is `git` | With `repo: dashboard`, the skills under a repository's `.factory/skills/` are ignored and its skills come from the dashboard only. `AGENTS.md`, `.factory/memory/`, `factory.yaml` and `schedules.yaml` are still read from git. The seed keys are described in the [kojo.yaml reference](/docs/config-reference/); changing the setting later is an admin action in the dashboard, see [Dashboard or git](/docs/manage/git/#dashboard-or-git).
The Skills studio for a draft of fix-bug: four steps across the top (Edit, Test, Eval, Activate), a form with the description, model tier and tools, and a validation panel.
The dashboard's Skills studio works with either source: activating a draft writes a revision where the source is dashboard, and opens a pull request where it is git.
## Resolution order For every session kōjō resolves one set of skills, by name, from three layers: 1. `repo`: the repository's `.factory/skills/`, plus skills activated in the dashboard for that repository. 2. `org`: the org's skills, from the dashboard or from the shared skills repository. 3. `builtin`: the skills compiled into the binary. See [Built-in skills](/docs/built-in-skills/). The first layer that defines a name wins. How one name resolves for a repository: ```mermaid flowchart TD N["A skill name"] --> L{"Allowed by the repository's skills list?"} L -- no --> X["Does not resolve"] L -- yes --> R{"Defined in the repo layer?"} R -- no --> O{"Defined in the org layer?"} R -- yes --> RV{"Valid, and its kit inside the egress limits?"} RV -- yes --> UR["The repo skill is used"] RV -- "no: reported as a problem" --> O O -- no --> B{"Built-in skill of that name?"} O -- yes --> OV{"Valid, and its kit inside the egress limits?"} OV -- yes --> UO["The org skill is used"] OV -- "no: reported as a problem" --> B B -- yes --> UB["The built-in skill is used"] B -- no --> X ``` The rules that follow from the code: - **An override replaces the whole skill.** Layers are not merged file by file. A repository skill with only a `SKILL.md` has no goals and an empty kit; it does not inherit the built-in `goals.yaml` or `kit.yaml`. Copy all three files and edit them. - **Each resolved skill records what it shadows.** `kojo skills list` and the dashboard show the layer a skill comes from and the lower layers that define the same name. - **A broken skill is skipped.** If a skill fails to parse or validate, resolution falls through to the next layer's version and the problem is reported as `/`. - **The directory name must equal `name`** in the front matter, or the skill is reported as a problem. - **Kits must stay inside the admin's egress limits.** A repository or org skill whose kit names an egress host or a credential that the scope's limits do not allow is skipped and reported, and the next layer's version of that name is used instead. Built-in kits are part of the release and are not checked against the limits. - **A repository can be limited to some skills.** When the repository's entry in the `repos` config object lists `skills`, only those names resolve for it. - **Within a layer, the dashboard wins.** A skill activated in the dashboard for a scope replaces the git skill of the same name in that layer. Deleting the dashboard copy hands the name back: the layer's git skill of that name applies again, and without one the next layer's. A deleted copy does not hide a git skill (in 0.3.0 and earlier it did): to keep a git skill from running, remove it from git, or leave it out of the repository's `skills` list. - **Built-in skills are read-only.** "Customise" in the dashboard copies one into a draft for the org or a repository. - **The version is recorded.** When a session starts, the commit or revision of every skill it resolved is stored on the session, so its replay shows which version ran. ## factory.yaml `.factory/factory.yaml` holds a repository's own settings. In this version it has one key. | Key | Type | Meaning | |---|---|---| | `merge_policy` | object | Replaces the org's merge policy for this repository. | | `merge_policy.mode` | string | `draft_only`, `ask` or `auto_merge`. Default `draft_only`. | | `merge_policy.trigger_permission` | string | Ignored in this file. Who may trigger work is the org's setting. | | `merge_policy.inherit` | boolean | Ignored in this file. kōjō uses it internally to take an override back. | | `merge_policy.merge_method` | string | `merge`, `squash` or `rebase`. Default `squash`. | | `merge_policy.risk.max_changed_lines` | integer | Diff size, in lines, at which size alone is high risk. Default 400. | | `merge_policy.risk.sensitive_paths` | list of globs | Paths that make a change high risk. Default: a built-in list. | | `merge_policy.risk.low_below` | number | Scores below it are low risk. Default 0.3. | | `merge_policy.risk.high_above` | number | Scores above it are high risk. Default 0.6. | | `merge_policy.risk.classifier` | boolean | Adds a fast-tier model's opinion to the rules. Default false. | ```yaml merge_policy: mode: ask merge_method: squash risk: max_changed_lines: 200 ``` The file is copied into the repository's config scope on a push to the default branch and before a session starts, with the author `git:`. It replaces the org's mode, merge method and risk rules as a whole: fields you leave out take the defaults above, not the org's values. Two things a repository cannot decide for itself: - **Who may trigger work.** `trigger_permission` in the file is ignored; the org's value is kept. - **Auto-merge.** `auto_merge` is treated as `ask` unless an admin allowed auto-merge for the repository. What the modes do is on the [Merge policy](/docs/merge-policy/) page. Unknown keys are rejected. A `factory.yaml` that does not parse or validate is reported as a problem and changes nothing: the policy from the last good version of the file stays. Deleting `factory.yaml`, or its `merge_policy` key, takes the override back, and the org's policy applies again. That only undoes an override that came from git. A merge policy an admin set for the repository in the dashboard is left alone. While the file holds the merge policy, an edit of the repository's merge policy made in kōjō (the dashboard, the API, MCP or `kojo config apply`) opens a pull request that changes the file instead of writing a revision. The dashboard's form shows the org's `trigger_permission` and does not let you change it. See [Editing a setting that lives in git](/docs/manage/git/#editing-a-setting-that-lives-in-git). ## List and validate skills `kojo skills list` asks a running server what a repository resolves to. It needs `--server` and a token; see the [CLI reference](/docs/cli/). ```sh kojo skills list --repo github/acme/api ``` | Column | Meaning | |---|---| | `NAME` | The skill. | | `LAYER` | `repo`, `org` or `builtin`, and the layers it overrides. | | `TIER` | The model tier. | | `WRITES` | Whether the skill can change the workspace. | | `DESCRIPTION` | The front matter's description, shortened. | Without `--repo` it lists the org's skills. Skills that failed to load are printed to standard error as `problem: /: `. `kojo skills validate` checks files on disk without a server. Each argument is a skill directory or a directory of skill directories. ```sh kojo skills validate .factory/skills ``` ```text ok fix-bug (10 tool(s), 2 check(s)) FAIL triage: unknown tool "bash" ``` It parses the three files exactly as the server does and exits 1 when a skill does not validate or a directory holds no `SKILL.md`. Run it in CI on changes to `.factory/`; the [Skills CI](/docs/skills/ci/) action runs it, and the skills' evals, on every pull request that changes them. It does not know the admin's egress limits: a kit that asks for more than they allow validates here and is skipped by the server. ## JSON Schemas The schemas are generated from the structs that load the files, so they match what the binary accepts. Print one with `kojo schema`, or use the published copy. | File | Command | Published | |---|---|---| | `SKILL.md` front matter | `kojo schema skill` | [skill.schema.json](/schema/skill.schema.json) | | `goals.yaml` | `kojo schema goals` | [goals.schema.json](/schema/goals.schema.json) | | `kit.yaml` | `kojo schema kit` | [kit.schema.json](/schema/kit.schema.json) | | `factory.yaml` | `kojo schema factory` | [factory.schema.json](/schema/factory.schema.json) | `kojo schema` without a name lists every schema. The schemas describe keys and types; the rules in the tables of [SKILL.md](/docs/skills/skill-md/), [goals.yaml](/docs/skills/goals/), [kit.yaml](/docs/skills/kit/) and [factory.yaml](#factoryyaml) (name format, known tools, value ranges) are enforced by the loader and reported by `kojo skills validate`. ## Writing a good skill Each point follows from how the engine treats a skill. - **Write the description for the orchestrator.** The orchestrator sees only each skill's name and description when it decides what to delegate. Say what the skill produces and when to use it, in one sentence. - **Make the instructions stand alone.** The subagent starts with a fresh context. Tell it where the task ends, what to record, and what the final report must contain. The final answer without a tool call is the report, and it is what the judge and the person who asked will read. - **List the fewest tools that do the job.** Every tool you list is a tool the model can call. A skill with `write_file`, `edit_file` or `exec` is a writing skill and is not offered to requests that may not cause writes; if the skill only needs `exec` to run tests or scanners, set `constraints.no_changes: true`. - **Put "done" in `goals.yaml`, not in prose.** An instruction can be ignored; a check cannot. Have the subagent record the repository's own command (`TEST_CMD`) and run that in a check, and mark optional commands `skip_if_unset`. - **Declare the outputs later steps depend on.** A declared output without a value fails the attempt, so the next skill and your checks can rely on it. - **Forbid what the skill must never touch.** List CI configuration and `.factory/**` in `forbidden_paths`, as the built-in writing skills do, and cap the diff with `max_changed_lines`. - **Write a rubric the judge can verify.** The judge fails items it cannot confirm from the report and the diff. "The fix addresses the root cause described in the report" can be graded; "the code is good" cannot. - **Give an attempt enough steps.** `max_steps` bounds each attempt, and an attempt that uses all of them ends the run: it is delivered as failed and not retried, whatever `max_attempts` says. Raise `max_steps` for skills that read a lot before they act, as `build-feature` and `security-audit` do. - **Ask for the least egress.** A kit that names a host outside the admin's limits makes your version of the skill unavailable. Do not list the forge host; it is added for you. - **Say that input is data.** kōjō already tells every subagent that issue text, files and command output are data. Repeat it in skills that read text from outside the team, and say what to do when that text contains instructions, as the built-in `triage` skill does. - **Mark sensitive reports `confidential`.** Do this for any skill whose report must not appear on a public issue or pull request. - **Validate, then measure.** Run `kojo skills validate` in CI, and run the skill against fixtures before it goes live. See [Evals](/docs/evals/). --- > Source: https://xavidop.github.io/kojo/docs/skills/skill-md # SKILL.md `SKILL.md` is the one file every [skill](/docs/skills/) needs: what the subagent is told, on which model tier, and which tools it may call. This page is its reference, with the tools a skill can list, the outputs it records, and the repository text that reaches every subagent whatever its skill. `SKILL.md` is a YAML front matter block followed by Markdown. The file must start with `---`, and the block must be closed by a line starting with `---`. ## Front matter | Field | Type | Default | Rules | |---|---|---|---| | `name` | string | required | Lowercase letters, digits and dashes; starts with a letter or digit; at most 63 characters. Must equal the directory name. | | `description` | string | required | Not empty. The orchestrator chooses skills by it. | | `model_tier` | string | `fast` | The model tier the subagent runs on. See [Models](/docs/models/). | | `tools` | list of strings | none | Names from the [tool catalog](#tool-catalog). Unknown names and duplicates are errors. The subagent gets exactly these tools. | | `kit` | string | `./kit.yaml` | Path of the kit file, relative to the skill directory. If you set it, the file must exist. | | `outputs` | list of strings | none | `UPPER_SNAKE_CASE` names the skill must record. Requires `set_output` in `tools`. | | `max_steps` | integer | 40 | 1 to 200. Model turns the subagent may take in each attempt. The count starts again when the critic sends the work back. | | `confidential` | boolean | false | Keeps the session's final report off public places. See below. | Unknown fields are rejected. `confidential: true` matters when a session's result is posted as a comment on an issue or pull request of a repository that is not private: the comment then only says that the report is confidential and links to the session in the dashboard. The flag also means the session never gets a [shareable report](/docs/observability/reports/), whatever `settings/reports` says. Those are the only two places it acts: a report delivered to a chat thread, the description of a pull request the session opens, and comments a skill posts itself with the `comment` tool are not withheld. ## Body The Markdown after the front matter is the subagent's instructions. It must not be empty. It becomes the start of the subagent's system prompt, followed by text kōjō adds: - The environment: where the repository is checked out (`/workspace`), that network access is limited to an allowlist, that it must not commit or push, the outputs it must record, and that its final answer without a tool call is its report. - The repository's `AGENTS.md`, when it has one. - The repository knowledge from `.factory/memory/`. - What kōjō [remembers](/docs/memory/): the preferences of the person who asked, the lessons maintainers taught this skill in reviews of its earlier pull requests in the repository, and up to five team memory entries that match the task. The user message holds the task and the values recorded so far in the session. A subagent starts with a fresh context: it sees nothing of the orchestrator's conversation or of earlier subagents except those values. ## Tool catalog A skill lists the tools its subagent may call. The model is only offered those tools, and a call to any other tool is refused. This is the whole catalog. A [follow-up](/docs/surfaces/triggers/#follow-ups) on one of kōjō's pull requests gives every subagent `get_review_comments` and `get_check_runs` as well, whatever its skill lists. | Tool | Runs in | Arguments | What it does | |---|---|---|---| | `read_file` | sandbox | `path`, `start_line`, `end_line` | Reads a text file with line numbers. Output stops at 24 KiB; read on with `start_line`. Files over 1 MiB and binary files are refused. | | `list_files` | sandbox | `dir`, `glob` | Lists tracked and untracked files that `.gitignore` does not hide. At most 500 paths. | | `search` | sandbox | `pattern`, `path`, `ignore_case` | Searches the workspace for an extended regular expression. At most 200 matching lines. | | `write_file` | sandbox | `path`, `content`, `purpose` | Creates or overwrites a file. At most 1 MiB. | | `edit_file` | sandbox | `path`, `old_string`, `new_string`, `replace_all`, `purpose` | Replaces an exact string. It must occur once unless `replace_all` is set. | | `exec` | sandbox | `command`, `timeout_seconds`, `purpose` | Runs a shell command from the repository root. Default timeout 600 seconds, at most 3600. Output is capped at 24 KiB. | | `git_diff` | sandbox | none | Shows every change made to the workspace in the session so far. | | `set_output` | core | `name`, `value` | Records a named value. See [Skill outputs](#skill-outputs). | | `memory_search` | core | `query` | Searches team memory of the repository and the org, and the personal memory of whoever asked. Returns up to five entries, each marked `team` or `personal`. | | `memory_save` | core | `topic`, `content`, `scope` | Saves one fact, 1 to 2000 characters. `scope: team` (the default) saves to the repository's team memory and is refused in sessions that may not write. `scope: personal` saves to the [personal memory](/docs/memory/#per-person-memory) of whoever asked. Stores nothing in a dry run. | | `get_issue` | core | `number` | Reads an issue and its comments. Without a number, the session's own issue. | | `list_issues` | core | `state`, `since_hours`, `limit` | Lists issues, without pull requests. `state` is `open` (default), `closed` or `all`; `limit` defaults to 30. | | `list_pull_requests` | core | `state`, `since_hours`, `limit` | Lists pull requests, the most recently updated first, each with its state, draft flag, author, branches, times (`merged_at` when merged) and body, clipped to 1,000 bytes. `state` is `open` (default), `closed` (closed without merging), `merged` or `all`; a merge counts as an update for `since_hours`; `limit` defaults to 30, at most 100. | | `get_pr` | core | `number` | Reads a pull request. | | `get_pr_diff` | core | `number` | Reads the diff of a pull request, clipped in the middle when large. | | `comment` | core | `body` | Posts a comment on the issue or pull request the session is about. At most three per run; recorded but not posted in a dry run. | | `get_review_comments` | core | `number` | Reads the review of a pull request: the comments on lines of its diff, with file, line and diff hunk, and the text of each review with its verdict. Without a number, the session's own pull request. The newest 100, each body clipped to 4,000 characters. | | `get_check_runs` | core | `number`, `sha`, `failed_only` | Reads the checks of a commit with their state and, where the forge keeps it, their output, cut to its last 8 KiB. By default the head of the session's pull request (in a follow-up, the commit the session started from). At most 40 checks. | Tools that run in the core use kōjō's own forge client and store. They do not go through the sandbox and need no egress. `write_file`, `edit_file` and `exec` are the tools that can change the workspace. A skill that lists one of them and does not set `no_changes: true` is a writing skill. Each of them takes an optional `purpose`, one line on why the change is made: a reviewer sees it next to the lines the call wrote, in the pull request's description and in the dashboard ([where each changed line came from](/docs/observability/#where-each-changed-line-came-from)). A failing tool call is returned to the model as an error it can act on. It does not fail the session. ## Skill outputs An output is a named, one-line value a skill records with `set_output`: a command, a path, a count. - `outputs:` in the front matter lists the names the skill must record. The goal critic rejects an attempt while one of them has no value. A value an earlier skill of the session recorded under the same name counts. - A name is `UPPER_SNAKE_CASE`, at most 64 characters, and must not start with `KOJO_`. A value is one non-empty line of at most 2000 characters. - A skill may record names it did not declare. The built-in `build-feature` skill records `BUILD_CMD` and `LINT_CMD` when the repository has them. - Outputs are kept on the session. Later skills of the same session receive them as "Values recorded so far", checks read them as `${NAME}`, the orchestrator sees them in the skill's result, and the session's result lists them. This is how the built-in skills hand work to each other: `reproduce-bug` records `REPRO_TEST` and `REPRO_CMD`, and `fix-bug` has a check that runs `${REPRO_CMD}` and a constraint that forbids changing `${REPRO_TEST}`. ## AGENTS.md and .factory/memory Two kinds of repository text reach every subagent, whatever its skill: - **`AGENTS.md`** at the repository root is appended to the system prompt as "The repository's AGENTS.md". It is cut at 24 KiB. - **`.factory/memory/`** files are concatenated in path order, each under a heading with its path, and appended as "Repository knowledge (.factory/memory)". The total is cut at 24 KiB. Use it for conventions and architecture notes that do not belong in `AGENTS.md`. Both are read from the default branch with the skills. They are instructions from the repository's maintainers, so treat changes to them like changes to code. Team memory is separate: it is stored in the database, written by `memory_save`, from the dashboard and from maintainers' reviews, and searched per task. Files under `.factory/memory/` are not copied into it. See [Memory](/docs/memory/). --- > Source: https://xavidop.github.io/kojo/docs/skills/goals # goals.yaml The goal critic holds every attempt of a [skill](/docs/skills/)'s subagent to this file. Read this page to write acceptance criteria, or to understand why a result was rejected. `goals.yaml` defines when the skill's result is accepted. The file is optional; unknown keys are rejected. | Key | Type | Default | Rules | |---|---|---|---| | `max_attempts` | integer | 3 | 1 to 10. How many times the subagent may try. | | `checks` | list | none | Commands run in the sandbox, in order. | | `checks[].name` | string | required | Unique within the file. | | `checks[].run` | string | required | A shell command, run from the repository root. | | `checks[].timeout` | duration | `10m` | Go duration syntax: `90s`, `15m`, `1h`. | | `checks[].expect_failure` | boolean | false | The command must exit non-zero. | | `checks[].skip_if_unset` | boolean | false | Skip the check while a `${NAME}` it uses has no value. | | `checks[].on_base` | boolean | false | Run the check on the code from before the pull request, with the session's changes on top. See [below](#checks-against-the-code-from-before-the-pull-request). | | `constraints.max_changed_lines` | integer | 0 | Cap on added plus removed lines. 0 means no cap. | | `constraints.forbidden_paths` | list of globs | none | Files the skill must not change. | | `constraints.required_paths` | list of globs | none | At least one changed file must match one of them. | | `constraints.allowed_paths` | list of globs | none | Every changed file must match one: added, modified, deleted, and both sides of a rename. `@tests` matches test files. | | `constraints.no_changes` | boolean | false | The workspace must be left untouched. Cannot be combined with `required_paths`. | | `judge.rubric` | string | required with `judge` | What a model grades the result against. | | `judge.model_tier` | string | `strong` | The tier of the judge. |
The goals form of the Skills studio for write-tests: a check new tests see the change with Must fail, Skip while a variable is unset and On the code from before the pull request ticked, then the constraints on the diff with Allowed paths @tests, Forbidden paths and Required paths side by side, and the judge rubric.
The dashboard's Skills studio edits the same fields as a form: each check with its options, and the constraints on the diff side by side.
## Checks Each check is a command that must exit 0. All checks run after every attempt, in file order; a failed check does not stop the ones after it. The last 4000 characters of a failed check's output go back to the subagent with the verdict. `expect_failure: true` inverts a check: it passes when the command exits non-zero. The built-in `reproduce-bug` skill uses it to require that the new test fails before any fix exists. A command that hits its `timeout` never passes, whether or not failure was expected. ## Checks against the code from before the pull request `on_base: true` runs a check on the code the pull request started from, with the session's own changes on top. With `expect_failure: true` it means "fails without the change": the built-in `write-tests` skill uses it to require that its new tests fail on the code from before the pull request and so actually test the change. The check runs in the workspace itself, not in a separate checkout, so installed dependencies, virtual environments and generated files are still there and a new test cannot fail on the base for want of them. For the run, the goal critic: 1. Takes the files the pull request changed that the session did not change. 2. Checks them out at the pull request's merge base, and deletes the ones the pull request added. 3. Runs the check with `KOJO_ON_BASE=1` set. 4. Restores those files from the pull request's head, where the workspace started. 5. Checks that the workspace's tree is the one from before the check. If it is not, for example because the check left a build artefact that `.gitignore` does not cover, the goal fails as an error that names the files. The files are restored after a timeout or a failed run too. A file the session changed keeps the session's version during the run. Linked repositories are not swapped. Before a skill with an `on_base` check runs on a pull request, kōjō finds the pull request's merge base in the sandbox: it fetches the base branch, up to 200 commits, and asks git for the merge base with the pull request's head. When the base branch moved more than that, it fetches the commit the forge names as the pull request's base and up to 200 more commits of the head, and tries again. The result, or the reason there is none, is kept for the rest of the session. In an [eval case](/docs/evals/#issues-and-pull-requests) the base is the case's pull request diff applied in reverse. `KOJO_PR_BASE` holds the merge base's commit, in every `exec` of the subagent and every check, once it is known. A subagent can read the pull request's change to a file with `git diff "$KOJO_PR_BASE" -- `. What the check reports when it cannot run: - **Skipped** on a session without a pull request, such as `kojo run --skill write-tests` with a task. It does not count as passed or failed. - **Unverified** on a pull request whose merge base was not found. The attempt is not rejected, since the subagent cannot fix that, but the result is published only as a draft, with the reason in its description. - A check with `skip_if_unset: true` whose value is unset is skipped as any other check is, before any of this. ```mermaid flowchart TD C["on_base check, value set"] --> PR{"Session on a pull request?"} PR -- no --> S["Reported skipped"] PR -- yes --> MB{"Merge base found?"} MB -- no --> U["Reported unverified: the pull request stays a draft"] MB -- yes --> SW["Files the pull request changed and the session did not: checked out at the merge base, added ones deleted"] SW --> RUN["Run with KOJO_ON_BASE=1"] RUN --> RS["Those files restored from the pull request's head"] RS --> T{"Tree as before?"} T -- no --> E["The goal fails as an error"] T -- yes --> R["Pass or fail as any check; expect_failure inverts"] ``` ## Values in checks `${NAME}` in a `run` command is replaced by a value. Values come from, in rising priority: 1. The `inputs` of the request: `kojo run --input NAME=value`, the `inputs` of an API request, or an eval case, see [Evals](/docs/evals/). Names starting with `KOJO_` are reserved, and an input named `reference.` is a [reference repository](/docs/skills/reference-repositories/). 2. What earlier skills of the same session recorded, for the names they declare in `outputs`. A value an earlier skill recorded without declaring it is shown to later skills but never reaches their checks, so a value a model chose, such as `true`, cannot pass another skill's check. 3. What this skill recorded with `set_output` during the run being checked. How a value is placed depends on the command: - When the whole command is one variable, as in `run: ${TEST_CMD}`, the value runs as written. This grants nothing new: it runs in the sandbox the subagent already has a shell in. - When the variable is part of a longer command, as in `run: go test -run ${TEST_NAME} ./...`, the value is quoted for the shell and stays a single argument. When a variable has no value, the check fails without running, and the subagent is told which value it did not record. With `skip_if_unset: true` the check is skipped instead and counts as passed. Use it for commands not every repository has, such as a linter. ## Constraints Constraints bound the diff of one run of the skill: what changed in the workspace since this skill started, not since the session started. Files hidden by `.gitignore` are not part of the diff. - `forbidden_paths` and `required_paths` are globs where `**` crosses directories: `.github/**`, `**/*_test.go`. - A `forbidden_paths` entry may contain `${NAME}`, for example `"${REPRO_TEST}"`. While that value is unset the entry is skipped. - `required_paths` is met by a file that was added or modified, not by a deletion. - `allowed_paths` is the other way round: every changed file must match one of its entries, whether it was added, modified or deleted. A renamed file is a deletion and an addition, so both its old and its new path must be allowed. An entry may be a glob, a glob with `${NAME}` in it, or `@tests`. - `@tests` matches test files: files under a directory named `test`, `tests`, `__tests__`, `spec`, `specs`, `testdata`, `e2e`, `__snapshots__` or `__mocks__` (and a few more), and files named as the common languages name tests, such as `*_test.go`, `test_*.py`, `*_test.py`, `conftest.py`, `*.test.ts`, `*.spec.js`, `*_spec.rb`, `*Test.java`, `*_test.sh` and `*.bats`. The full rules are in [internal/testpaths/testpaths.go](https://github.com/xavidop/kojo/blob/main/internal/testpaths/testpaths.go); history evals use the same rules. - An `allowed_paths` entry whose `${NAME}` has no value matches nothing, and the failure names the value. A list whose entries all name unset values allows no change at all. - `no_changes: true` also changes how the skill is classified: a skill with `no_changes` counts as read-only even if it lists `exec`. Requests from actors who may not trigger write actions only reach read-only skills. See [Who may trigger what](/docs/surfaces/triggers/#what-an-untrusted-session-may-do). Constraints and checks need a sandbox. A skill that lists no sandbox tool and has no checks runs without one, and its constraints are not evaluated. ## The judge `judge` adds a rubric that a model grades the result against. It runs only when every deterministic criterion has passed, so no model call is spent on work that already failed. The judge sees the rubric, the task, the subagent's final report, the recorded values, how many comments were posted, the names and states of the checks, the diff, and, for a session on a pull request, the pull request's own diff (at most 60 KiB; a longer one loses its middle), so it can tell whether the work follows the pull request's change. It is told to fail anything it cannot verify from that evidence and to trust the diff over the report. Write rubric items as statements that can be checked against the report and the diff. One item per line. ## How the goal critic uses it After every attempt the goal critic checks, in order: that each declared output has a value and there is a final report; the constraints on the diff; the checks; then the judge. If anything is unmet, the same subagent receives the list of unmet criteria and the failing output and tries again, up to `max_attempts`. The result of the last attempt is delivered either way, with the report of what is unmet. A subagent that uses all its `max_steps` is not retried. The place of the critic in a session is described in [Concepts](/docs/concepts/). One skill run, from the first attempt to the verdict that is delivered: ```mermaid flowchart TD A["The subagent ends an attempt"] --> D["Outputs and report, constraints, every check"] D --> E{"All met?"} E -- no --> F{"Attempts left, and max_steps not used up?"} E -- "yes, no judge" --> OK["Accepted"] E -- "yes, with a judge" --> J{"Judge's verdict"} J -- pass --> OK J -- "unmet rubric items" --> F J -- "no verdict, twice" --> ER["The skill run ends with an error"] F -- yes --> R["Unmet criteria and failing output go back to the same subagent"] R --> A F -- no --> X["Rejected: delivered with the report"] ``` --- > Source: https://xavidop.github.io/kojo/docs/skills/kit # kit.yaml Every [skill](/docs/skills/) runs in a sandbox, and its kit says what that sandbox gets. Read this page when a skill needs more than the default image, hosts of its own or a setup step. `kit.yaml` describes the sandbox the skill runs in. The file is optional; unknown keys are rejected. | Key | Type | Default | Meaning | |---|---|---|---| | `image` | string | the deployment's image | Container image of the sandbox. Empty uses `sandbox.image` from `kojo.yaml`, or the toolchain image published with the release. | | `resources.cpu` | string | none | CPU request, in Kubernetes quantity syntax: `"4"`. At most the deployment's `sandbox.max_resources.cpu`. | | `resources.memory` | string | none | Memory request: `8Gi`. At most `sandbox.max_resources.memory`. | | `resources.disk` | string | none | Size of the workspace: `40Gi`. At most `sandbox.max_resources.disk`. | | `needs_docker` | boolean | false | The skill wants its own Docker daemon in the sandbox. | | `egress.allow` | list of strings | none | Hosts the sandbox may reach, on ports 443 and 80, or `host:port` for another port. Everything else is denied. | | `credentials` | list | none | Credentials the proxy injects, by name. | | `credentials[].name` | string | required | Unique within the kit. | | `credentials[].hosts` | list of strings | none | Hosts the credential is sent to, with the port when it is not 443 or 80. Each must be covered by `egress.allow`. | | `credentials[].scope` | string | none | Documentation only: what the credential is for, such as `contents:read`. It is not enforced. | | `setup` | list of strings | none | Shell commands run in the workspace before the skill's first run in a session. | There is no `env` or `secrets` key. A kit never carries a secret, only the name of a credential the deployment holds. **Egress.** An entry is a hostname or a `*.domain` pattern, which allows ports 443 and 80, or either followed by a port, `registry.example.com:5000`, which allows that port only. A port is a number from 1 to 65535. A bare `*`, a path or a user is refused. You do not list the forge: kōjō adds the host the repository is cloned from, and the clone credential for it, to every sandbox of the session. kojo-proxy sets that credential only on git's fetch. A push, a writing API call or an API read from a sandbox goes out without it, on every forge; with the `sbx` driver, deny rules refuse them. On GitHub the credential is also short-lived and limited to the repository; on GitLab and Forgejo it is the configured token. See [Security](/docs/security/). A repository or org kit must stay inside the scope's egress limits (`settings/egress`), which only an admin edits. A new install starts with the Go, npm, PyPI, crates.io, Maven Central and RubyGems registries, the vulnerability databases `vuln.go.dev` and `api.osv.dev`, and the configured forges' hosts: every host a built-in kit names. How the allowlist is enforced is on the [kojo-proxy](/docs/sandboxes/proxy/#egress-allowlists) page. **Credentials.** A credential name must be on the scope's `allowed_credentials` list. A name resolves only when it is the forge of the session's own repository (`github`, `gitlab` or `forgejo`), and then only to that repository's clone credentials. Any other name is an error when the sandbox is set up. **Resources.** What a driver does with each quantity is in [Resources, timeouts and lifetime](/docs/sandboxes/#resources-timeouts-and-lifetime). A deployment can cap every kit with `sandbox.max_resources` in `kojo.yaml`: a kit that asks for more gets the cap, and one that asks for less keeps its own. The `docker` driver also lowers CPU and memory to what the Docker daemon has. A kit is not refused for asking for more than the machines have; on Kubernetes its sandbox fails when no node can take its pod (see [Scheduling](/docs/sandboxes/k8s/#scheduling)). **Docker.** `needs_docker` is honoured where the sandbox driver can provide a Docker daemon. Where it cannot, the skill still runs, without Docker, and the subagent is told so in its instructions. **Setup.** Setup commands run before the skill's first run in a session, with the kit's egress allowlist in force. They run once per skill and session: a second run of the same skill does not repeat them, and each skill of a session runs its own, even when two skills share a sandbox. Each command is recorded as a step of the session and has 10 minutes. A failing command stops the skill before it starts. Setup runs before the starting point of the skill's diff is taken, so files it creates do not count against the skill's [constraints](/docs/skills/goals/#constraints); files that `.gitignore` does not hide are still part of the session's change. **Image.** When two skills of a session name different images, the session creates a second sandbox and copies the workspace into it. On the `k8s` driver the sandbox runs with no capability and cannot gain privileges, even when the image runs as root, so setup cannot install system packages (`apt-get` switches users and changes file owners): put them in the image. Writing under the image's own directories still works for the user that owns them. --- > Source: https://xavidop.github.io/kojo/docs/skills/reference-repositories # Reference repositories A session works on its own repository. A request can name others for the skills to read next to it: reference repositories. kōjō clones each one into a fixed directory of the workspace, and nothing in that directory ever becomes part of the session's change. The built-in [`port-sdk`](/docs/built-in-skills/changing-code/#port-sdk) skill uses one to port a change from another implementation of an SDK; a skill of your own can use them for anything that needs a second repository to read: a client checked against its server's API, docs checked against the code they describe. Reference repositories are read-only and belong to one request: the request names them, the skills read them, and nothing of them is published. To change several repositories of one product in one session, link them instead: a [linked repository](/docs/multi-repo/) is configured once for a repository in the `repos` object, is cloned into every session on it at `.kojo/linked/`, may be changed when the requester may change it, and gets a pull request of its own when it changed. ## Naming one A reference repository is the request input `reference.`. The name is the directory it gets: lowercase letters, digits and dashes. The value says which repository, and optionally which part of it the work is about: | Value | What is checked out | What comes with it | |---|---|---| | `github/acme/sdk-python` | The default branch | Nothing | | `github/acme/sdk-python@v1.5.0` | That branch, tag or commit | Nothing | | `github/acme/sdk-python#412` | The head of pull request 412 (GitLab: `!412` works too) | The pull request's diff and its description | | `github/acme/sdk-python@v1.4.0..v1.5.0` | The end of the commit range | The diff of the range | A session takes at most four. A request gets them in one of these ways: - `kojo run --reference github/acme/sdk-python#412` names the reference `source`; `--reference upstream=github/acme/api@v2` gives it another name. The flag can be repeated. - An API request carries `"inputs": {"reference.source": "github/acme/sdk-python#412"}`. - A mention on a forge can name one repository the way forges write a reference to another repository: `acme/sdk-python#412` or `acme/sdk-python@v1.5.0`, with or without the forge in front. The first one that is an enabled repository on the same forge, and that the mention [may have](#who-may-name-one), becomes the reference `source`. Any other is ordinary text. - A follow-up of a merged pull request (`on_merge` of the `repos` object) attaches that pull request as `source`. See [`port-sdk`](/docs/built-in-skills/changing-code/#port-sdk) for a configuration. A follow-up on the repository the pull request was merged in attaches no reference: it works on the default branch, which holds the merge, and reads the pull request with `get_pr_diff`. It runs only for a merge into the default branch. ## Where it is in the workspace ```text /workspace/ the session's repository └── .kojo/refs/ ├── source/ the checkout, a git repository of its own ├── source.diff the change: a pull request's diff, or a commit range's └── source.md a pull request's title, author, state, link and description ``` - The clone is 50 commits deep and its `HEAD` is detached at what the request named. - A pull request's diff and description are read by the core through the forge's API and written next to the checkout. The diff is cut at 2 MiB. A commit range's diff is made by git in the sandbox. - git in the workspace ignores `.kojo/refs/` (an entry in `.git/info/exclude`), and the core leaves the directory out of every diff it takes, whatever is staged. So nothing under it shows in `git_diff`, counts for a constraint, is seen by the judge, or is pushed. A file a subagent copies out of it into the repository is part of the change like any other file. - Each subagent is told in its system prompt which reference repositories exist, where they are, and what they are about. What people wrote about the change, a pull request's title and description, stays in the `.md` file and reaches the model as a file it reads. - `read_file` reads paths under `.kojo/refs/`. `list_files` and `search` cover the session's repository only, so a skill that explores a reference needs `exec`: `git -C .kojo/refs/source ls-files`, `git -C .kojo/refs/source grep -n pattern`. - When a session uses a second sandbox image, the reference repositories are copied over with the workspace. - A pull request the session opens has a "References" section in its description: the name, the repository, the pull request or commits, the commit that was read, and the link. - A repository that tracks files of its own under `.kojo/refs/`, or has a symbolic link at `.kojo`, cannot be worked on with reference repositories: the session fails when it prepares the workspace. ## How it is cloned The sandbox holds no credential, and the kit of the skill does not need the reference's host. The core clones a reference repository itself, before the first skill runs, with a clone credential that the forge adapter issues for that repository, the same way it issues the session's own. ```mermaid sequenceDiagram participant C as Core participant F as Forge adapter participant P as Proxy participant S as Sandbox C->>S: clone the session's repository, with its own clone credential C->>F: clone credential for the reference repository C->>P: policy of the sandbox, now the reference's git host and that credential only C->>S: git fetch into .kojo/refs/source C->>P: policy of the sandbox, the skill's again Note over S: the skill starts, the reference is a directory ``` While a skill runs, the forge's credential in the proxy is the one of the session's own repository. A skill that should fetch more of a reference than the clone holds cannot; name the ref or the range it needs in the request. ## Who may name one A reference repository is read with kōjō's access, not the requester's. Four rules decide. The first two are checked when the request is accepted, again when the session starts, and again each time a clone credential is resolved: - **The request is trusted.** It comes from an operator (the CLI, the API, the dashboard), from a mention by someone with the repository's `trigger_permission`, or from an `on_merge` follow-up an operator configured. Any other request that names one is rejected. - **The repository is enabled** in the `repos` object, on a configured forge, and is not the session's own. kōjō does not read a repository it was not enabled on. A repository that is disabled while a session runs is no longer cloned. - **In a mention, the author can read it.** The author needs at least read access to the repository they name, unless it is not private. - **A private repository is not read for a public one.** A session that can publish on a repository that is not private does not get a private reference repository. A dry run is exempt: it publishes nothing. A request that names a reference repository it may not have is rejected, and a session whose reference stops being allowed fails. A mention is the exception, because people cite other repositories for many reasons: there the repository is left out, the mention is handled as if it had not named one, and the refusal is in the audit log as `reference.refuse`. ## In a skill of your own A skill does not declare reference repositories; the request brings them, under the names the skill's instructions expect. Say the name in the instructions, and make a missing one a failed check instead of a guess: ```markdown --- name: check-client description: Check this API client against the server's routes in the reference repository `server` and report every call that no longer matches. model_tier: strong tools: [read_file, list_files, search, exec] --- The server this client talks to is the reference repository `server`, checked out at `.kojo/refs/server`. List its routes, then find every call in this repository that does not match one. Change nothing. ``` ```yaml # goals.yaml max_attempts: 2 checks: - name: server is attached run: test -d .kojo/refs/server constraints: no_changes: true judge: rubric: | - Every reported mismatch names the call in this repository and the route in the server. ``` ```sh kojo run --repo github/acme/client --skill check-client --reference server=github/acme/api@v2 ``` ## In an eval fixture An eval case has no forge to clone from. A case brings its reference repositories as files: a `references/` directory next to `repo/`, with one directory per reference and, optionally, `.diff` and `.md` beside it. The engine places them under `.kojo/refs/` where a clone would be and makes each directory a git repository with one commit. ```text evals/fixtures/port-sdk/truncate/ ├── case.yaml ├── repo/ the target, as the workspace └── references/ ├── source/ the source after its change ├── source.diff └── source.md ``` --- > Source: https://xavidop.github.io/kojo/docs/skills/example # Worked example: fix-bug These are the three files of the built-in `fix-bug` skill, from [skills/fix-bug](https://github.com/xavidop/kojo/blob/main/skills/fix-bug/SKILL.md). Each file has its own reference page: [SKILL.md](/docs/skills/skill-md/), [goals.yaml](/docs/skills/goals/) and [kit.yaml](/docs/skills/kit/). `SKILL.md`: ```md --- name: fix-bug description: Write a minimal, tested fix for a bug, ideally one that already has a failing reproduction test. model_tier: strong tools: [get_issue, read_file, list_files, search, write_file, edit_file, exec, git_diff, memory_search, set_output] outputs: [TEST_CMD] --- You receive a bug report and, when one exists, a failing reproduction test (`REPRO_TEST`, run with `REPRO_CMD`). 1. Find the root cause. Read the code path the reproduction exercises until you can state the cause in one sentence. Do not patch symptoms. 2. Make the smallest change that makes the reproduction pass. 3. Do not modify the reproduction test. If you believe the test itself is wrong, stop and say why instead of editing it. 4. Run the full test suite of the affected package or module, and the linter if the repository has one. Fix what you broke. 5. Record with `set_output` `TEST_CMD`: one shell command, run from the repository root, that runs the test suite of the affected package. 6. Finish with: the root cause in one or two sentences, what you changed and why that is the right place, and anything a reviewer should look at twice. No unrelated refactors, renames or formatting changes. Follow the repository's conventions (AGENTS.md, surrounding code). If there is no reproduction test, add a regression test for the fix. ``` `goals.yaml`: ```yaml max_attempts: 3 checks: - name: reproduction passes run: ${REPRO_CMD} skip_if_unset: true timeout: 15m - name: package tests pass run: ${TEST_CMD} timeout: 30m constraints: max_changed_lines: 300 forbidden_paths: ["${REPRO_TEST}", ".github/**", ".gitlab-ci.yml", ".forgejo/**", "bitbucket-pipelines.yml", ".factory/**"] judge: rubric: | - The fix addresses the root cause described in the analysis, not a symptom. - No unrelated refactors. - The reproduction test was not weakened, skipped or deleted. - The code follows the repository's conventions (see AGENTS.md). ``` `kit.yaml`: ```yaml resources: { cpu: "4", memory: 8Gi, disk: 40Gi } needs_docker: true egress: allow: - proxy.golang.org - sum.golang.org - registry.npmjs.org - pypi.org - files.pythonhosted.org - crates.io - static.crates.io - index.crates.io - repo.maven.apache.org - rubygems.org ``` How the pieces work together: - The subagent must record `TEST_CMD`. The check `package tests pass` then runs exactly that command, so the skill works in any repository without a hard-coded test command. - `REPRO_CMD` and `REPRO_TEST` come from an earlier `reproduce-bug` run in the same session. When there was none, the first check is skipped and the `${REPRO_TEST}` constraint does not apply. - The constraints keep the fix small and keep it away from CI configuration and from `.factory/` itself. - The judge runs last and grades what commands cannot: root cause, scope, conventions. - The kit names no image, so the deployment's default toolchain image is used, and no credentials: the clone credential for the repository is added by kōjō. --- > Source: https://xavidop.github.io/kojo/docs/skills/ci # Skills CI A repository that keeps its own [skills](/docs/skills/) under `.factory/skills/` can check them on every pull request that changes them, before they reach the default branch, where kōjō reads them. The kōjō repository is also a GitHub Action that does this: it validates each changed skill, runs its [evals](/docs/evals/) on cases the repository keeps next to it, and reports the result in one comment on the pull request. This page is for teams that write skills and want them checked like code. ## What the action does 1. Installs `kojo`, the latest release or the one `version` names, from the release's archive. The archive's SHA-256 must be the one the release's `checksums.txt` lists, as with the [install script](/docs/install/). 2. Finds the skills to check. On a pull request these are the skills it changes: a file under `.factory/skills//` or `.factory/evals//`, or a recordings file named `.yaml`. The `skills` input changes this. 3. Runs `kojo skills validate` on each, which parses its three files as the server does. 4. For each valid skill that has cases under `.factory/evals//`, runs `kojo eval --local --factory .factory --json`. Each case runs as a dry run in a throwaway sandbox, a plain container on the runner's Docker (the `docker` driver), and passes when the goal critic accepts the result. 5. Writes the report to the job summary and to one comment on the pull request, which it updates on later pushes. 6. Fails the step when a skill does not validate, when a skill's pass rate is below the minimum, or when an eval does not run to the end. It needs a Linux runner with Docker, such as `ubuntu-latest`. ## A workflow This workflow checks the skills of every pull request that changes `.factory/`, with recorded model answers, so it needs no model key: ```yaml name: Skills on: pull_request: paths: [".factory/**"] permissions: contents: read pull-requests: write jobs: skills: runs-on: ubuntu-latest timeout-minutes: 30 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - uses: xavidop/kojo@v0 with: recordings: .factory/recordings ``` `xavidop/kojo@v0` follows the latest `v0` release of the action. To pin it, use the full commit SHA of a release instead, with the version in a comment, as above for `actions/checkout`. With a live model instead of recordings, pass the provider's key from a secret. Each case then costs what its model calls cost, and the minimum pass rate defaults to 0.7: ```yaml - uses: xavidop/kojo@v0 with: provider: anthropic api-key: ${{ secrets.ANTHROPIC_API_KEY }} ``` With a `kojo.yaml` of your own, for a provider that needs more than a key (`vertexai`, `bedrock`, `azure`, `ollama`), prices, budgets or another sandbox image: ```yaml - uses: xavidop/kojo@v0 with: config: .factory/kojo.ci.yaml env: ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} ``` The file must name the `docker` driver and `dev: true`, as [the config the action writes](#the-config-the-action-writes) does. ## Permissions The action needs these two, and nothing else: | Permission | For | |---|---| | `contents: read` | Checking out the repository. | | `pull-requests: write` | Listing the files the pull request changes, and writing and updating the comment. | A pull request from a fork gets a read-only token and no secrets. The action then cannot comment: it logs a warning, and the report is in the job summary. A live model cannot be called without its key either, so recordings are what works on forks. Do not run the action on `pull_request_target` to get around this: that event runs the fork's skills, cases and kits with the base repository's token and secrets. ## The repository's layout ```text .factory/ ├── skills/ │ └── changelog-entry/ # a skill, as the server reads it │ ├── SKILL.md │ ├── goals.yaml │ └── kit.yaml ├── evals/ │ └── changelog-entry/ # the skill's name │ ├── fixed-timeout/ # a case │ │ ├── case.yaml │ │ ├── reference.patch # optional │ │ └── repo/ # the repository the skill works on │ └── new-feature/ │ ├── case.yaml │ └── repo/ └── recordings/ └── changelog-entry.yaml # model answers for the cases, if you replay ``` A case has the layout of the built-in fixtures: [Fixtures](/docs/evals/#fixtures) describes `case.yaml`, `repo/`, `reference.patch` and the issues and pull requests a case can seed, and [Write a new case](/docs/evals/#write-a-new-case) how to design one. A file of a case keeps its executable bit. A symbolic link that leads out of `.factory/` is not followed. A skill with cases under `evals//` is evaluated on those cases alone. A valid skill without any is reported as validated only and does not fail the step. A directory under `evals/` for a skill the repository does not define evaluates the built-in skill of that name on the repository's cases. The server does not read `evals/` or `recordings/`: they are for the action, and for `kojo eval --local --factory` on your machine. The [kōjō repository's test](https://github.com/xavidop/kojo/tree/main/testdata/skills-ci) has a complete example: the `changelog-entry` skill, two cases and their recordings. ## Inputs | Input | Default | Meaning | |---|---|---| | `version` | `latest` | The kōjō release to install, such as `v0.3.0`. The action needs a release whose `kojo eval` has `--factory`, and says so when it does not. | | `kojo-path` | | A `kojo` binary to use instead of installing a release, such as one an earlier step built. | | `working-directory` | `.` | The directory that holds `.factory/`, relative to the workspace. `kojo` runs there, and `config` and `recordings` are relative to it. | | `skills` | `changed` | `changed`: on a pull request, the skills it changes; on any other event, all of them. `all`: every directory under `.factory/skills/` and `.factory/evals/`. Otherwise, skill names separated by spaces, commas or new lines. | | `config` | | A `kojo.yaml` for the evals. Without it, the action writes one. | | `recordings` | | A directory of recorded model answers. The config the action writes then replays them, and no key is needed. Not with `config`: set `models.recordings` in it instead. | | `provider` | `anthropic` | The model provider of the config the action writes when there are no recordings: `anthropic`, `openai`, `googleai` or `openrouter`. | | `api-key` | | The provider's API key, from a secret. Without it, `kojo` reads the provider's usual variable, such as `ANTHROPIC_API_KEY`, from the step's environment. | | `fast-model` | `claude-haiku-5-5` for `anthropic` | The model of the `fast` tier. Required for the other providers. | | `strong-model` | `claude-opus-5-5` for `anthropic` | The model of the `strong` tier. Required for the other providers. | | `sandbox-image` | `alpine/git` (pinned) | The image of a sandbox whose kit names none, in the config the action writes. The cases of the example need only `sh` and `git`; set the image your cases need, or `image` in the skill's `kit.yaml`. | | `min-pass-rate` | the config's | Fail when a skill's pass rate is below this, 0 to 1. Without it, `seed.activation.min_eval_pass_rate` of the config applies: 1 with recordings and 0.7 with a live model in the config the action writes, 0 in a config that sets none. | | `comment` | `true` | Write the report as a comment on the pull request. `false` leaves it in the job summary only. | | `github-token` | `${{ github.token }}` | The token that lists the pull request's files and writes the comment. | ## Outputs | Output | Value | |---|---| | `passed` | `true` when every skill checked passed, `false` otherwise. | | `skills` | The skills checked, separated by spaces. | | `report` | The path of the report in Markdown: the body of the comment. | | `results` | The path of the results in JSON: per skill, the validation output and the eval run as `kojo eval --json` prints it. | ## Keyless runs with recordings The mock model provider answers model calls from recorded answers instead of calling a model ([Recordings](/docs/evals/#recordings) has the format). Only the model is replaced: the tool calls in a recording run for real in the sandbox, and the skill's checks really run. A replayed eval therefore checks the skill's goals, its kit and its cases against fixed answers, which is what a pull request that changes a check or a constraint needs. It does not measure how a model does with changed instructions: record again when you change `SKILL.md`, and run against a live model when that is the question. To record the answers, run the evals once against a live model with `KOJO_LIVE_MODELS=1` and `KOJO_RECORD=1`. Write a config with real tiers and a recordings directory, for example `kojo.record.yaml`: ```yaml dev: true server: public_url: http://localhost:8080 database: url: postgres://unused@localhost/unused # not opened by --local models: gateway: embedded recordings: out/recordings # where the answers are written tiers: fast: { provider: anthropic, model: claude-haiku-5-5 } strong: { provider: anthropic, model: claude-opus-5-5 } providers: anthropic: api_key: "${ANTHROPIC_API_KEY}" sandbox: driver: docker image: alpine/git:v2.54.1@sha256:27279f417b0d0f6267fe22468fb12ecc2dd84783e6b44a6642d1c31f61e174b7 ``` Then, from the repository root, with Docker running: ```sh KOJO_LIVE_MODELS=1 KOJO_RECORD=1 kojo eval changelog-entry --local -f kojo.record.yaml --factory .factory --min-pass-rate 0 ``` Every answer is written under `out/recordings/recorded/`, one file per session and purpose (`subagent:`, and `judge:` when the skill has a judge). To keep them: 1. Read each file. A recording holds what the model said, tool calls included: make sure no key or token is in it. 2. Add a `match` to each recording: a string that occurs in its case's task and in no other case of the skill, such as the issue number. A recorded file has none. 3. Put them in `.factory/recordings/.yaml`, one file per skill, so that a pull request that changes the recordings checks that skill. Check the result the way the action will: ```sh kojo skills validate .factory/skills/changelog-entry kojo eval changelog-entry --local -f kojo.replay.yaml --factory .factory ``` where `kojo.replay.yaml` is the record config with `recordings: .factory/recordings`, both tiers `{ provider: mock, model: replay }` and no `providers`. In the kōjō repository, `make record` does the same for the built-in skills; see [Live models and recording](/docs/evals/#live-models-and-recording). ## The config the action writes Without `config`, the action writes a `kojo.yaml` like this one, with the recordings directory made absolute: ```yaml dev: true server: public_url: http://localhost:8080 database: url: postgres://unused@localhost/unused models: gateway: embedded recordings: "/home/runner/work/app/app/.factory/recordings" tiers: fast: { provider: mock, model: replay } strong: { provider: mock, model: replay } sandbox: driver: docker image: "alpine/git:v2.54.1@sha256:27279f417b0d0f6267fe22468fb12ecc2dd84783e6b44a6642d1c31f61e174b7" seed: activation: min_eval_pass_rate: 1 ``` Without recordings the tiers name `provider`, `fast-model` and `strong-model`, the key is read from the environment as `api_key: "${SKILLS_CI_API_KEY}"` (it is never written to the file), and `min_eval_pass_rate` is 0.7. `dev: true` is what the `docker` driver requires; [The docker driver](/docs/sandboxes/docker/) says what it isolates. The store is in memory and nothing is kept after the job. ## The comment The comment starts with a hidden marker that names the working directory, so the action finds and updates its own comment, and two uses of the action with different `working-directory` values keep one comment each. It shows: | Part | What | |---|---| | Status | **Passed** with the number of skills checked, or **Failed** with how many did not pass. | | Table | One row per skill: whether it is valid, its pass rate with passed and total cases, the number of cases, and the cost of its eval. A skill without cases shows `none`; a skill whose eval did not run shows `error`; a skill the pull request deletes shows `removed`. | | Bar and models | The minimum pass rate the skills were held to, and the models of the tiers, `mock/replay` when the answers are recorded. | | Folded details | For each evaluated skill, its cases: result, the critic's attempts, cost, and similarity to `reference.patch` when the case has one; for a failed case, the session's error or the critic's report. For a skill that does not validate, what `kojo skills validate` said. For an eval that did not run, kojo's error. | | Footer | A link to the workflow run, and the commit checked. | Text that came from a model or a repository is shown in code blocks only, where a mention notifies nobody. When the details would make the comment longer than GitHub allows, the comment leaves them out and says that the job summary has them. The comment is updated in place on each push. A push that no longer changes any skill turns it into "This pull request changes no skill". A pull request that never changed a skill gets no comment. Cost is what kōjō computes from the `price` of each tier ([Prices and cost](/docs/models/#prices-and-cost)). The config the action writes sets no price, so it shows $0.00: give a config of your own with prices to see, and with `models.budgets`, bound what a live run costs. ## Run it from a checkout of kōjō `kojo-path` runs the action with a binary built from source instead of a release. The kōjō repository tests the action that way in [skills-ci.yml](https://github.com/xavidop/kojo/blob/main/.github/workflows/skills-ci.yml), on `testdata/skills-ci`: ```yaml - run: go build -o "$RUNNER_TEMP/kojo" ./cmd/kojo - uses: ./ with: kojo-path: ${{ runner.temp }}/kojo working-directory: testdata/skills-ci skills: changelog-entry recordings: .factory/recordings comment: "false" ``` --- > Source: https://xavidop.github.io/kojo/docs/built-in-skills # Built-in skills kōjō ships fourteen skills in its binary. This page summarises them, lists what their kits have in common and shows how to override one. The built-in skills are the last layer of [skill resolution](/docs/skills/#resolution-order). They use the same three files as your own skills. Each has its own directory under `skills/` in the kōjō repository, embedded by [skills/embed.go](https://github.com/xavidop/kojo/blob/main/skills/embed.go). Three pages, one per kind of work, say what each skill is told to do, the acceptance criteria it is held to and the sandbox it gets, so you can decide which to use as they are and which to override: - [Changing code](/docs/built-in-skills/changing-code/): `build-feature`, `reproduce-bug`, `fix-bug`, `port-sdk`, `write-tests` and `docs-sync`. - [Reviews and audits](/docs/built-in-skills/reviews-and-audits/): `review-pr`, `security-audit` and `triage`, which report and change nothing. - [Scheduled upkeep](/docs/built-in-skills/scheduled-upkeep/): `dependency-review`, `daily-digest`, `stale-issue-triage`, `flaky-test-hunt` and `release-watch`, the jobs meant for a schedule. ## Summary | Skill | Usually started by | Produces | Tier | Writes code | |---|---|---|---|---| | [`build-feature`](/docs/built-in-skills/changing-code/#build-feature) | A feature request | Code, tests and docs, `TEST_CMD`, `ACCEPTANCE` | `strong` | Yes | | [`reproduce-bug`](/docs/built-in-skills/changing-code/#reproduce-bug) | The orchestrator, on a bug report | A failing test, `REPRO_TEST`, `REPRO_CMD` | `strong` | Yes | | [`fix-bug`](/docs/built-in-skills/changing-code/#fix-bug) | The orchestrator, on a bug report | A fix, `TEST_CMD` | `strong` | Yes | | [`port-sdk`](/docs/built-in-skills/changing-code/#port-sdk) | A request that names the source repository, or a merge in it | The same change in this repository's language, `TEST_CMD`, `SOURCE_CHANGE`, `DIFFERENCES` | `strong` | Yes | | [`write-tests`](/docs/built-in-skills/changing-code/#write-tests) | A pull request | Tests, `TEST_CMD`, `NEW_TESTS_CMD` | `strong` | Yes (test files only) | | [`docs-sync`](/docs/built-in-skills/changing-code/#docs-sync) | A pull request, or a merge | Docs edits, or a report | `fast` | Yes (docs only) | | [`review-pr`](/docs/built-in-skills/reviews-and-audits/#review-pr) | A new or updated pull request | One review comment | `strong` | No | | [`security-audit`](/docs/built-in-skills/reviews-and-audits/#security-audit) | A request or a schedule | A confidential report, `FINDINGS`, `HIGHEST_SEVERITY` | `strong` | No | | [`triage`](/docs/built-in-skills/reviews-and-audits/#triage) | A new issue | One triage comment, `CATEGORY` | `fast` | No | | [`dependency-review`](/docs/built-in-skills/scheduled-upkeep/#dependency-review) | A schedule | Dependency upgrades and a report, `TEST_CMD` | `strong` | Yes | | [`daily-digest`](/docs/built-in-skills/scheduled-upkeep/#daily-digest) | A schedule | A digest of the last day | `fast` | No | | [`stale-issue-triage`](/docs/built-in-skills/scheduled-upkeep/#stale-issue-triage) | A schedule | A verdict per stale issue | `fast` | No | | [`flaky-test-hunt`](/docs/built-in-skills/scheduled-upkeep/#flaky-test-hunt) | A schedule | A table of flaky tests, memory entries | `strong` | No | | [`release-watch`](/docs/built-in-skills/scheduled-upkeep/#release-watch) | A schedule | A report of upstream releases, memory entries | `fast` | No | How to read the table: - **Usually started by** is the intended use. Nothing is wired up on a new install: no skill runs on a forge event until an operator maps the event to it in the repository's `auto` setting (the events are `issue_opened`, `pr_opened`, `pr_updated` and `check_failed`), no skill follows a merge in another repository until an operator lists it under that repository's `on_merge`, and no schedule exists until someone creates one. Any skill can also be chosen by the orchestrator from its description, or run directly with `kojo run --skill `. See [Automatic triggers](/docs/surfaces/triggers/#automatic-triggers-per-repository) and [Schedules](/docs/schedules/). - **Tier** is the model tier of the subagent. Which model a tier means is on the [Models](/docs/models/) page. - **Writes code** is how the engine classifies the skill: it lists `write_file`, `edit_file` or `exec` and does not set `no_changes: true`. Requests from people who may not trigger write actions only reach the skills marked "No". When a writing skill changes the workspace, the change is published as the repository's [merge policy](/docs/merge-policy/) allows: a draft pull request by default. Skills that do not write end with a report. The report is posted as a comment when the session is about an issue or pull request, sent to the chat thread when the request came from chat or a schedule with `notify`, and kept on the session in every case. ## What the kits have in common Every built-in kit leaves `image` empty, so the skill runs on the deployment's default sandbox image. None lists credentials: kōjō adds the repository's forge host and its clone credential itself. That credential is set only on git's fetch, so a sandbox can fetch with it but not push or read the forge's API, on every forge and every driver (with `sbx`, the driver's deny rules refuse the rest outright). On GitHub it is also short-lived and limited to the repository; on GitLab and Forgejo it is the configured token. See [Security](/docs/security/). Several kits allow the same ten package registry hosts. The skill pages call them "the package registries": ```text proxy.golang.org sum.golang.org registry.npmjs.org pypi.org files.pythonhosted.org crates.io static.crates.io index.crates.io repo.maven.apache.org rubygems.org ``` Five kits set `needs_docker: true`. That is honoured where the sandbox driver can give the sandbox its own Docker daemon. Where it cannot, the skill runs without Docker and its subagent is told so. See [Sandboxes](/docs/sandboxes/). ## Overriding a built-in skill To change a built-in skill for one repository: 1. Copy the skill's three files from `skills//` in the kōjō repository to `.factory/skills//` in your repository. Copy all three: an override replaces the whole skill, and a missing `goals.yaml` or `kit.yaml` means no goals or an empty kit, not the built-in ones. 2. Edit them. Keep `name` equal to the directory name. 3. Check the result: ```sh kojo skills validate .factory/skills ``` 4. Merge to the default branch. kōjō reads `.factory/` from the default branch on the next push webhook or session. 5. Confirm which version is in use. The `LAYER` column shows `repo (overrides builtin)`: ```sh kojo skills list --repo github/acme/api ``` This works when the repository's skills are edited in git, which is the default. To change a skill for every repository, or to edit in the browser, use "Customise" in the dashboard's Skills studio; see [the Skills studio](/docs/manage/dashboard/#skills-studio). Your copy's kit is checked against the egress limits an admin set; the built-in kits are not. The default limits cover every host a built-in kit names: the package registries, `vuln.go.dev`, `api.osv.dev` and the configured forges. A copy of any built-in skill therefore loads without widening them. If an admin has narrowed the limits, a copy whose kit names a host outside them is skipped and the built-in version stays in use. --- > Source: https://xavidop.github.io/kojo/docs/built-in-skills/changing-code # Changing code Six built-in skills change code: `build-feature` builds a feature, `reproduce-bug` and `fix-bug` turn a bug report into a failing test and then a fix, `port-sdk` carries a change from one implementation of an SDK to another, and `write-tests` and `docs-sync` add the tests and the documentation a pull request is missing. Their change is published as the repository's [merge policy](/docs/merge-policy/) allows: a draft pull request by default. "The package registries" in the kits are the ten hosts listed under [What the kits have in common](/docs/built-in-skills/#what-the-kits-have-in-common). How to change one of these skills for a repository is under [Overriding a built-in skill](/docs/built-in-skills/#overriding-a-built-in-skill). ## build-feature Builds a feature end to end from an issue or a request: understand, plan, implement with tests and docs, verify. | | | |---|---| | Tier | `strong` | | Tools | `get_issue`, `read_file`, `list_files`, `search`, `write_file`, `edit_file`, `exec`, `git_diff`, `memory_search`, `memory_save`, `set_output` | | Outputs | `TEST_CMD`, `ACCEPTANCE` | | Steps per attempt | 120 | **What it does.** The instructions are nine steps, in order: 1. **Understand.** Read the request and every comment, write the acceptance criteria as observable behaviours, and record them as `ACCEPTANCE`. Where the request leaves a choice open, take the one that matches how the repository already does similar things and say so. If it cannot be built without an answer only a maintainer has, stop and ask. 2. **Learn the codebase.** Read AGENTS.md, search team memory, and read the closest existing feature completely, including how it is wired in. 3. **Find the commands.** Work out how the repository builds, tests and lints, run the tests of the area once, and record `TEST_CMD`. When the repository has them, also record `BUILD_CMD` and `LINT_CMD`. 4. **Plan.** List the files to add or change, the smallest set that satisfies the criteria. 5. **Implement.** In the style of the surrounding code, with input validation at the boundary, a migration when stored data changes and a config default when a setting is added. 6. **Test.** Add tests for every acceptance criterion, including at least one failure case. 7. **Document.** Update what describes the feature to a user. 8. **Verify.** Run the build, the linter and the tests, then read its own diff and remove what is not part of the feature. 9. **Report.** The criteria and how each is met, the choices made, what was left out, what to look at twice. Save one line to team memory when it learned an unwritten convention. Its limits: one feature, one change; no changes to CI configuration, deployment manifests or `.factory/`; no weakening of existing tests. **Goals.** ```yaml max_attempts: 3 checks: - name: builds run: ${BUILD_CMD} skip_if_unset: true timeout: 20m - name: tests pass run: ${TEST_CMD} timeout: 30m - name: lint run: ${LINT_CMD} skip_if_unset: true timeout: 15m constraints: max_changed_lines: 1500 # A feature without a test is not done. required_paths: ["**/*test*", "**/*spec*", "**/tests/**", "**/test/**", "**/__tests__/**"] forbidden_paths: [".github/**", ".gitlab-ci.yml", ".forgejo/**", "bitbucket-pipelines.yml", ".factory/**"] judge: rubric: | - Every acceptance criterion recorded in ACCEPTANCE is implemented, and the report says where. - Each criterion has a test that would fail without the implementation, and at least one failure case is tested. - The feature is wired in end to end (reachable through the route, command, config or API it is meant for), not only implemented as an unused function. - User-facing docs describe the new behaviour. - No unrelated refactors, renames or formatting changes; no existing test was weakened. - The code follows the repository's conventions (see AGENTS.md). ``` The build and lint checks run only when the subagent recorded their commands. The change must touch at least one test file. **Kit.** 4 CPUs, 8Gi memory, 40Gi disk. `needs_docker: true`. Egress: the package registries. **Outputs.** `TEST_CMD` and `ACCEPTANCE` are required; `BUILD_CMD` and `LINT_CMD` are recorded when they exist. The feature is in the workspace. **Override.** Copy to `.factory/skills/build-feature/`. If your repository always has a build and a lint command, add them to `outputs` in `SKILL.md` and drop `skip_if_unset` from their checks, so a run that skips them is rejected. Raise or lower `max_changed_lines` to the size of feature you want delivered in one change. ## reproduce-bug Turns a bug report into a failing automated test, without fixing the bug. | | | |---|---| | Tier | `strong` | | Tools | `get_issue`, `read_file`, `list_files`, `search`, `write_file`, `edit_file`, `exec`, `git_diff`, `memory_search`, `set_output` | | Outputs | `REPRO_TEST`, `REPRO_CMD` | | Steps per attempt | 40 (default) | **What it does.** It reads the report and finds the code involved, then finds out how the repository runs tests (AGENTS.md, the Makefile, CI config, package manifests) and runs the existing tests of the affected package once. It writes the smallest test that exercises the reported behaviour and asserts the expected behaviour, next to the existing tests and in their style. It runs the test, which must fail on the assertion about the reported behaviour, not on a compile error or a typo. It records `REPRO_TEST`, the path of the test file, and `REPRO_CMD`, one command that runs only that test. It must not change non-test code or fix the bug. If the report cannot be reproduced, it says what it tried instead of writing a test that fails for another reason. **Goals.** ```yaml max_attempts: 3 checks: - name: reproduction fails before the fix run: ${REPRO_CMD} expect_failure: true timeout: 15m constraints: max_changed_lines: 200 required_paths: ["**/*test*", "**/*spec*", "**/tests/**", "**/test/**"] forbidden_paths: [".github/**", ".gitlab-ci.yml", ".forgejo/**", "bitbucket-pipelines.yml", ".factory/**"] judge: rubric: | - The new test targets the behaviour described in the bug report. - The test output shows an assertion failing for the reported reason, not a build or setup error. - Only test code changed. - REPRO_CMD runs just the new test. ``` The check runs the recorded command and passes only when it exits non-zero within 15 minutes. **Kit.** 4 CPUs, 8Gi memory, 40Gi disk. `needs_docker: true`, because a reproduction may need to build images or start services. Egress: the package registries. **Outputs.** `REPRO_TEST` and `REPRO_CMD`, which `fix-bug` uses later in the same session, and the new test in the workspace. **Override.** Copy to `.factory/skills/reproduce-bug/`. Adjust `required_paths` if your tests live in paths the four globs do not match. Keep the two output names: the built-in `fix-bug` reads them. ## fix-bug Writes a minimal, tested fix for a bug, ideally one that already has a failing reproduction test. | | | |---|---| | Tier | `strong` | | Tools | `get_issue`, `read_file`, `list_files`, `search`, `write_file`, `edit_file`, `exec`, `git_diff`, `memory_search`, `set_output` | | Outputs | `TEST_CMD` | | Steps per attempt | 40 (default) | **What it does.** It receives a bug report and, when one exists, a failing reproduction test (`REPRO_TEST`, run with `REPRO_CMD`). It finds the root cause until it can state it in one sentence, makes the smallest change that makes the reproduction pass, and does not modify the reproduction test; if it believes the test is wrong, it stops and says why. It runs the full test suite of the affected package and the linter if there is one, records `TEST_CMD`, and finishes with the root cause, what changed and why there, and what a reviewer should look at twice. No unrelated refactors, renames or formatting changes. Without a reproduction test, it adds a regression test for the fix. **Goals.** ```yaml max_attempts: 3 checks: - name: reproduction passes run: ${REPRO_CMD} skip_if_unset: true timeout: 15m - name: package tests pass run: ${TEST_CMD} timeout: 30m constraints: max_changed_lines: 300 forbidden_paths: ["${REPRO_TEST}", ".github/**", ".gitlab-ci.yml", ".forgejo/**", "bitbucket-pipelines.yml", ".factory/**"] judge: rubric: | - The fix addresses the root cause described in the analysis, not a symptom. - No unrelated refactors. - The reproduction test was not weakened, skipped or deleted. - The code follows the repository's conventions (see AGENTS.md). ``` The first check is skipped when no reproduction was recorded in the session. The second always runs. **Kit.** 4 CPUs, 8Gi memory, 40Gi disk. `needs_docker: true`. Egress: the package registries. **Outputs.** `TEST_CMD`, and the fix in the workspace. **Override.** Copy to `.factory/skills/fix-bug/`. Common changes are a stricter `max_changed_lines`, more `forbidden_paths`, and a fixed lint check in `goals.yaml` when your repository has one command for it. The three files are shown and explained in the [worked example](/docs/skills/example/). ## port-sdk Ports a change from another implementation of the same SDK to this repository: the same public API and behaviour, written the way this repository's language and conventions do it, with tests and docs. | | | |---|---| | Tier | `strong` | | Tools | `get_issue`, `read_file`, `list_files`, `search`, `write_file`, `edit_file`, `exec`, `git_diff`, `memory_search`, `memory_save`, `set_output` | | Outputs | `TEST_CMD`, `SOURCE_CHANGE`, `DIFFERENCES` | | Steps per attempt | 120 | **Inputs.** The skill needs the other repository as the [reference repository](/docs/skills/reference-repositories/) named `source`. The request names it, with the part of it the port is about: | `reference.source` | What is ported | |---|---| | `github/acme/sdk-python#412` | Pull request 412. The checkout is its head, and its diff and description are next to it. | | `github/acme/sdk-python@v1.4.0..v1.5.0` | A commit range. The checkout is its end, and its diff is next to it. | | `github/acme/sdk-python@v1.5.0` or `github/acme/sdk-python` | A feature the request names in words, found in the checkout of that ref or of the default branch. | kōjō clones the source into `.kojo/refs/source` of the workspace before the skill starts. Nothing under `.kojo/refs/` is ever part of the change. **What it does.** The instructions are ten steps, in order: 1. **Read the source change.** The diff, then the files it touches in the checkout: code, tests, docs, changelog. 2. **Map it.** Write down what the change means to a user of the SDK: public API, behaviour, defaults, errors, what crosses a process boundary (wire names, config keys, environment variables), and its test cases. What is internal to the source implementation is left out. Record the map as `SOURCE_CHANGE`. When nothing in the change can be observed by a user, or this repository already has it, there is nothing to port: the skill changes nothing and reports why. 3. **Learn how this repository says the same things.** Read AGENTS.md, search team memory, and read the closest existing feature here next to its counterpart in the source. That pair shows how names, optional arguments, errors and documentation were carried over before. 4. **Find the commands.** Run the tests of the area once and record `TEST_CMD`. When the repository has them, also record `BUILD_CMD` and `LINT_CMD`. 5. **Port.** Implement every item of the map. The behaviour is ported, not the text: this language's error type instead of an exception, an options value instead of keyword arguments. What users of both SDKs see as the same thing stays the same: wire names, config keys, error codes, documented defaults. 6. **Port the tests.** Every test case of the source change gets a test here with the same inputs and results, plus the cases this language makes possible. 7. **Docs and changelog.** In this repository's wording and format. 8. **Verify.** Run the build, the linter and the tests, then read its own diff and remove what is not part of the port. 9. **Differences.** List every place where the port deliberately differs from the source, and everything that could not be ported one to one, each with the reason. Record the list as `DIFFERENCES`, or `none`. 10. **Report.** The source change, where each item of the map is in this repository, the differences, and what to look at twice. Save one line to team memory when it settled a mapping that later ports should repeat. Its limits: this change and nothing else; nothing under `.kojo/refs/` is edited; no changes to CI configuration, deployment manifests or `.factory/`; no weakening of existing tests. **Goals.** ```yaml max_attempts: 3 checks: # The port is made from the reference repository, never from memory. - name: source is attached run: test -d .kojo/refs/source - name: builds run: ${BUILD_CMD} skip_if_unset: true timeout: 20m - name: tests pass run: ${TEST_CMD} timeout: 30m - name: lint run: ${LINT_CMD} skip_if_unset: true timeout: 15m # A port without a test is not done. A run that found nothing to port # changes nothing and passes. - name: a change comes with tests run: | changed=$(git -c safe.directory='*' status --porcelain) [ -z "$changed" ] || printf '%s\n' "$changed" | grep -Eiq 'test|spec' constraints: max_changed_lines: 1500 forbidden_paths: [".github/**", ".gitlab-ci.yml", ".forgejo/**", "bitbucket-pipelines.yml", ".factory/**"] judge: rubric: | - Every item of SOURCE_CHANGE (public API, behaviour, defaults, errors) is implemented in the diff, or is listed in DIFFERENCES with a reason. If SOURCE_CHANGE says there is nothing to port, the diff is empty and the report says why. - The port is idiomatic: names, optional arguments, errors and documentation follow this repository's language and its existing API, not the source language's. It is not a line-by-line translation. - What users of both SDKs see as the same thing is the same: defaults, error conditions, wire names, config keys. - Each ported behaviour has a test that would fail without the implementation, and at least one failure case is tested. - User-facing docs describe the new behaviour, and the changelog has an entry when the repository keeps one by hand. - The report names the source change it ports and lists every deliberate difference; it agrees with DIFFERENCES. - No unrelated refactors, renames or formatting changes; no existing test was weakened. ``` The first check fails a run that was started without a source. The last one lets a run with nothing to port pass with an empty diff, and requires a test file in any other change. The judge sees this repository's diff and the recorded `SOURCE_CHANGE`, not the source's code: that is why the map is a required output. **Kit.** 4 CPUs, 8Gi memory, 40Gi disk. No Docker. Egress: the package registries. The source repository's host is not in the kit: the core clones it. **Outputs.** `TEST_CMD`, `SOURCE_CHANGE` and `DIFFERENCES` are required; `BUILD_CMD` and `LINT_CMD` are recorded when they exist. The port is in the workspace, and becomes a pull request as the repository's [merge policy](/docs/merge-policy/) allows: a draft by default. Its description has a "References" section with the source repository, the pull request or commits, the commit that was read and the link. **Starting a port.** There are four ways, and in each the request must be allowed to [name the source](/docs/skills/reference-repositories/#who-may-name-one): it is trusted, and the source is an enabled repository. - From the CLI, with `--reference`: ```sh kojo run --repo github/acme/sdk-go --skill port-sdk --reference github/acme/sdk-python#412 kojo run --repo github/acme/sdk-go --skill port-sdk --reference github/acme/sdk-python@v1.5.0 "port the retry budget option" ``` - Through the API, as an input of the session: ```sh curl -X POST "$KOJO_SERVER/api/v1/sessions" \ -H "Authorization: Bearer $KOJO_TOKEN" -H "Content-Type: application/json" \ -d '{"repo": "github/acme/sdk-go", "skill": "port-sdk", "inputs": {"reference.source": "github/acme/sdk-python#412"}}' ``` - With a mention on an issue or pull request of the target repository, by writing the source the way forges write a reference to another repository: ```text @kojo port acme/sdk-python#412 ``` The orchestrator picks `port-sdk` from the request. The author needs the trigger permission on this repository and must be able to read the source. `kojo` stands for your bot's name. - As a follow-up: when a pull request is merged in the source repository, kōjō starts a port on every repository listed under its `on_merge`. The merged pull request is the `source` of each session. This configuration ports every pull request merged in the Python SDK to the TypeScript and Go SDKs. Apply it with `kojo config apply`, or edit the `repos` object: ```yaml version: 1 objects: - scope: org object: repos content: repos: github/acme/sdk-python: enabled: true on_merge: - skill: port-sdk repos: [github/acme/sdk-typescript, github/acme/sdk-go] github/acme/sdk-typescript: enabled: true github/acme/sdk-go: enabled: true ``` ```mermaid sequenceDiagram participant F as Forge participant C as Core participant S as Sandbox of sdk-go F->>C: webhook, pull request 412 merged in sdk-python Note over C: on_merge of sdk-python lists port-sdk on sdk-go C->>S: clone sdk-go into the workspace C->>S: clone sdk-python at the pull request into .kojo/refs/source C->>S: write source.diff and source.md, read from the forge API Note over S: port-sdk maps the change, ports it and tests it C->>S: goal critic runs the checks C->>F: draft pull request on sdk-go that names pull request 412 of sdk-python ``` A follow-up session may change code, as a session an operator started would: an operator wrote the follow-up, and the merge was made by someone the source repository allows to merge. A target that is not enabled is skipped and the refusal is audited. A merge is followed once, however often the forge reports it. A pull request that a follow-up opened starts no follow-up when it merges, and a port is not followed back to the repository it was made from, so two repositories that list each other do not port back and forth. A merged pull request with nothing a user of the SDK can observe ends as a session with a report and no pull request. **Override.** Copy to `.factory/skills/port-sdk/` in the target repository. Put the mapping between the two SDKs that your team has settled (naming, error types, what is never ported) into the target's AGENTS.md or `.factory/memory/` rather than into the skill, so every skill sees it. If your SDKs share generated code, add its paths to `forbidden_paths`. Tighten the last check to your test layout if `test|spec` is too loose for it. ## write-tests Writes tests for the lines a pull request changed, in the repository's own framework, that fail without the change when it changes behaviour. | | | |---|---| | Tier | `strong` | | Tools | `get_pr`, `get_pr_diff`, `get_issue`, `read_file`, `list_files`, `search`, `write_file`, `edit_file`, `exec`, `git_diff`, `memory_search`, `set_output` | | Outputs | `TEST_CMD` (required); `NEW_TESTS_CMD` when the pull request changes behaviour | | Steps per attempt | 40 (default) | **What it does.** It reads the pull request's diff and finds the changed lines that are not tests. It writes tests in the repository's own framework and style, next to the existing tests, and never edits a file that is not a test. It records `TEST_CMD`, a command that runs the affected tests. When the pull request changes behaviour (a feature or a fix), it also records `NEW_TESTS_CMD`, a command that runs only the new tests. When it does not (a refactor), it leaves `NEW_TESTS_CMD` unset and says in the report why behaviour is unchanged. Without a pull request, it writes tests for what the task names. **Starting it.** Mention kōjō on the pull request and ask for tests; list it under `auto.pr_opened` of the repository to run it on every new pull request (see [automatic triggers](/docs/surfaces/triggers/#automatic-triggers-per-repository)); or run `kojo run --repo github/acme/api --pr 412 --skill write-tests "write tests for this change"`. The tests come as a pull request of their own, stacked on the person's: its base is the pull request's branch. **Goals.** ```yaml max_attempts: 3 checks: - name: tests pass run: ${TEST_CMD} timeout: 30m - name: new tests pass run: ${NEW_TESTS_CMD} skip_if_unset: true timeout: 30m - name: new tests see the change run: ${NEW_TESTS_CMD} on_base: true expect_failure: true skip_if_unset: true timeout: 30m constraints: allowed_paths: ["@tests"] forbidden_paths: [".github/**", ".gitlab-ci.yml", ".forgejo/**", "bitbucket-pipelines.yml", ".factory/**"] max_changed_lines: 600 judge: rubric: | - The tests exercise the lines the pull request changed. - The assertions are specific: no tautologies, no snapshot of everything. - The tests follow the repository's existing framework and style. - No existing test was weakened or skipped. - When NEW_TESTS_CMD is unset, the report explains why the change keeps behaviour, and the diff agrees. ``` The first check runs the affected tests on the pull request's head, the new ones included. The second runs only the new tests there. The third runs them on the code from before the pull request, with the session's new test files on top, and must fail: tests that pass without the change do not test it. The second check is what stops a `NEW_TESTS_CMD` of `false` from passing the third. For a refactor both are skipped. `allowed_paths: ["@tests"]` fails any change outside test files, and the judge reads the pull request's diff next to the tests. How the core finds the code from before the pull request, and what happens when it cannot, is under [checks against the code from before the pull request](/docs/skills/goals/#checks-against-the-code-from-before-the-pull-request). When it cannot, the third check is unverified and the pull request stays a draft. ```mermaid sequenceDiagram participant PR as Pull request participant S as write-tests participant C as Goal critic PR->>S: get_pr_diff: the changed lines S->>S: tests next to the existing ones, TEST_CMD, NEW_TESTS_CMD when behaviour changes S->>C: report C->>C: only test files changed (allowed_paths @tests) C->>C: TEST_CMD and NEW_TESTS_CMD pass on the head C->>C: NEW_TESTS_CMD fails on the code from before the pull request (on_base) C->>C: judge reads the tests and the pull request's diff ```
The replay of a write-tests session: its goal critic open, with the checks tests pass, new tests pass, and new tests see the change marked on the base, exit 1, passed.
The session page of a write-tests run: the third check ran on the code from before the pull request and failed there, as it must.
**Kit.** The same as `fix-bug`: 4 CPUs, 8Gi memory, 40Gi disk. `needs_docker: true`. Egress: the package registries. **Outputs.** `TEST_CMD`, `NEW_TESTS_CMD` when the pull request changes behaviour, and the tests in the workspace. Only `TEST_CMD` is required, because a refactor has no `NEW_TESTS_CMD`. **Override.** Copy to `.factory/skills/write-tests/`. Common changes are naming your test command in the instructions, narrowing `allowed_paths` to your test directories (for example `["tests/**", "**/*_test.go"]`), and a smaller `max_changed_lines`. ## docs-sync Updates the documentation a pull request made untrue, and only that; reports what was checked when nothing needs changing. | | | |---|---| | Tier | `fast` | | Tools | `get_pr`, `get_pr_diff`, `read_file`, `list_files`, `search`, `write_file`, `edit_file`, `exec`, `git_diff`, `memory_search` | | Outputs | none | | Steps per attempt | 40 (default) | **What it does.** It reads the pull request's diff and lists every command, flag, config key, environment variable, path and behaviour the diff adds, renames or removes. It searches the documentation for each (the README, `docs/`, and every Markdown, MDX, reStructuredText and AsciiDoc file), and edits only what the change made untrue or left out, spelling each name as the diff does. It never writes a changelog entry and leaves unrelated documentation alone. When nothing needs updating, it changes nothing and says in the report what it searched for: that is a success, not a failure. **Starting it.** A mention on the pull request; `auto.pr_opened` of the repository; `kojo run --repo github/acme/api --pr 412 --skill docs-sync "bring the docs up to date"`; or after a merge, through `on_merge` naming the repository itself: ```yaml repos: github/acme/api: enabled: true on_merge: - skill: docs-sync repos: [github/acme/api] ``` Only a merge into the default branch starts it; a merge into another branch, such as a stacked pull request merged into the branch it stacks on, does not. The session clones the default branch, which holds the merged change, reads the pull request with `get_pr_diff`, and opens a pull request of its own against the default branch, whose description says `Follows #`. A pull request it opened starts no `on_merge` session when it merges. On an open pull request, its edits come as a pull request stacked on the person's. Each run opens one, so a skill under `auto.pr_updated`, which runs on every push, would open one per push. **Goals.** ```yaml max_attempts: 2 checks: - name: docs check run: ${DOCS_CHECK_CMD} skip_if_unset: true timeout: 15m constraints: allowed_paths: ["**/*.md", "**/*.mdx", "**/*.rst", "**/*.adoc", "docs/**"] forbidden_paths: ["CHANGELOG*", "**/CHANGELOG*", ".factory/**", ".github/**", ".gitlab/**", ".forgejo/**"] judge: rubric: | - Each edit follows from a change in the pull request's code. - Every command, flag, config key and path the edits add or rename is spelled as the pull request's diff spells it. - Docs unrelated to the change are untouched. - When nothing needed updating, the report says what was checked. ``` The docs check runs only when `DOCS_CHECK_CMD` has a value: a site build, a link checker, a script that compares the documented flags with the code. The value comes from the request (`kojo run --input DOCS_CHECK_CMD="make docs-check"`, or `inputs` in the API) or from a repository's override that writes the command into `goals.yaml`. The skill has no `set_output`, so the model cannot choose the command its own work is checked with. The judge reads the pull request's diff next to the edits. ```mermaid flowchart TD A["A pull request: a mention, auto, kojo run --pr"] --> R["Read the pull request's diff"] M["A merge: on_merge naming the repository itself, on the default branch"] --> R R --> E{"Did the change make any docs untrue?"} E -->|yes| W[Edit those docs only] E -->|no| N["Change nothing, say what was searched"] W --> K{"DOCS_CHECK_CMD given?"} N --> K K -->|yes| C[Run the docs check] K -->|no| J["Judge, with the pull request's diff"] C --> J J --> P["A pull request against the person's branch, or the default branch after a merge"] J --> Q["A report when nothing changed"] ``` **Kit.** 2 CPUs, 4Gi memory, 20Gi disk. No Docker. Egress: the package registries, because a docs check may install its tool. **Outputs.** None; the edits in the workspace, or a report. **Override.** Copy to `.factory/skills/docs-sync/`. Common changes are a fixed docs check in `goals.yaml` (`run: make docs-check` instead of `${DOCS_CHECK_CMD}`), `allowed_paths` narrowed to where your documentation lives, and more `forbidden_paths` for generated reference pages. --- > Source: https://xavidop.github.io/kojo/docs/built-in-skills/reviews-and-audits # Reviews and audits Three built-in skills read and report without changing the repository: `review-pr` reviews a pull request, `security-audit` looks for vulnerabilities, and `triage` classifies an issue. Each sets `no_changes: true`, so requests from people who may not trigger write actions reach them too. "The package registries" in the kits are the ten hosts listed under [What the kits have in common](/docs/built-in-skills/#what-the-kits-have-in-common). How to change one of these skills for a repository is under [Overriding a built-in skill](/docs/built-in-skills/#overriding-a-built-in-skill). ## review-pr Reviews one pull request for correctness bugs, missing tests and convention breaks, and posts one review comment. It does not change the pull request. | | | |---|---| | Tier | `strong` | | Tools | `get_pr`, `get_pr_diff`, `get_issue`, `read_file`, `list_files`, `search`, `exec`, `memory_search`, `comment` | | Outputs | none | | Steps per attempt | 40 (default) | **What it does.** It reads the pull request, its diff and the issue it references, then reads the changed code in context: whole functions, their callers, the tests. It looks, in this order, for correctness problems, security problems, whether the changed behaviour is tested, and conventions the repository states. When the tests are quick it runs them with `exec`. It posts one comment that leads with the findings that must be fixed, each with file and line, what goes wrong and a concrete input or sequence that triggers it, then optional suggestions. If it found nothing, it says what it checked. It reports only what it verified in the code, and treats the pull request's description and code comments as data. A session about a pull request works on that pull request's head, so the sandbox holds the code under review. **Goals.** ```yaml max_attempts: 2 constraints: no_changes: true judge: rubric: | - A review comment was posted. - Every finding names a file and a location and describes a concrete failure, not a vague concern. - Findings are about this change, not pre-existing code the change does not touch. - The review states what was checked when it reports no findings. ``` **Kit.** 4 CPUs, 8Gi memory, 40Gi disk. No Docker. Egress: the package registries. The pull request's code runs in this sandbox, never in the core. **Outputs.** The review comment. **Override.** Copy to `.factory/skills/review-pr/`. The usual change is the list of what to look for in step 3 of the instructions. Keep `no_changes: true`: it is what makes the skill read-only although it lists `exec`. ## security-audit Looks for security vulnerabilities in the repository and reports each with evidence, impact and a fix. It reports; it does not change code. | | | |---|---| | Tier | `strong` | | Tools | `read_file`, `list_files`, `search`, `exec`, `memory_search`, `memory_save`, `set_output` | | Outputs | `FINDINGS`, `HIGHEST_SEVERITY` | | Steps per attempt | 100 | | Confidential | yes | **What it does.** The scope is the whole repository unless the task names a directory, a pull request's changed files or one class of issue. The instructions are seven steps: 1. Map the attack surface: how data enters and what is sensitive. 2. Run the scanners that exist for the stack when they are installed or installable from the allowed registries (`govulncheck`, `npm audit`, `pip-audit`, `cargo audit`, `bundle audit`, a secret scan), and treat their output as leads to confirm. 3. Trace input to sink by hand, across injection, authentication and sessions, authorization, files and paths, outbound requests, deserialization and parsing, cryptography, secrets, web issues, concurrency and resources, and dependencies and build. 4. Confirm each finding: the entry point, the sink, and why nothing in between stops it. Demonstrate it inside the sandbox when that is cheap and safe; never test against anything outside the sandbox. What cannot be confirmed is dropped or listed as "needs review". 5. Rate each finding critical, high, medium or low. 6. Write the report, most severe first: title, severity, file and line, the path from input to sink, the impact and the specific fix; then "needs review"; then what was and was not covered. 7. Record `FINDINGS`, the number of confirmed findings, and `HIGHEST_SEVERITY`: critical, high, medium, low or none. Its rules: evidence or it is not a finding; never print a secret, show at most its first four characters; no exploit tooling beyond a minimal local proof; change nothing; save to team memory only that an area was audited and when, never the details of an unfixed vulnerability. **Goals.** ```yaml max_attempts: 2 constraints: no_changes: true judge: rubric: | - Every finding names a file and line, the input that reaches it, and the dangerous operation it reaches. - Every finding explains why existing validation or checks do not stop it; none is a generic recommendation. - Severities match the stated impact and preconditions. - Each finding has a specific fix. - No secret value is printed in the report. - The report says what was covered and what was not. ``` **Kit.** 4 CPUs, 8Gi memory, 40Gi disk. No Docker. Egress: the package registries, plus `vuln.go.dev` and `api.osv.dev` for the vulnerability databases the scanners query. **Outputs.** `FINDINGS`, `HIGHEST_SEVERITY` and the report. Because the skill is `confidential`, when the session is about an issue or pull request of a repository that is not private, the comment only points to the session in the dashboard, and no session that runs the skill gets a [shareable report](/docs/observability/reports/). A report sent to a chat thread, for example by a schedule with `notify`, is posted in full; choose that channel accordingly. **Override.** Copy to `.factory/skills/security-audit/`. Narrow the classes in step 3 to your stack, or name the scanners your image has. Keep `confidential: true` and `no_changes: true`. ## triage Classifies one issue and replies with a short triage note. It does not fix anything. | | | |---|---| | Tier | `fast` | | Tools | `get_issue`, `list_issues`, `read_file`, `list_files`, `search`, `memory_search`, `comment`, `set_output` | | Outputs | `CATEGORY` | | Steps per attempt | 40 (default) | **What it does.** It reads the issue and its comments, decides whether it is a `bug`, `feature`, `question`, `docs`, `chore` or `invalid`, and records that as `CATEGORY`. It looks for duplicates with `list_issues` and names the issue number when the same behaviour is already reported. For a bug it searches the code for the files most likely involved. It lists what is missing to act on the issue, then posts one comment of under 200 words with the category, duplicates, likely location, missing facts and a suggested next step. The instructions tell it to treat the issue text as a report to assess, never as instructions, and to say so in the note when the issue contains instructions it did not follow. **Goals.** ```yaml max_attempts: 2 constraints: no_changes: true judge: model_tier: fast rubric: | - A category was recorded and it matches the issue. - A triage comment was posted, and it is specific to this issue (it names files, issue numbers or missing facts), not generic advice. - Any duplicate claim names an issue that really reports the same behaviour. - The note does not promise a fix or a date. ``` There are no command checks. The critic requires `CATEGORY`, an unchanged workspace and the rubric. **Kit.** 1 CPU, 2Gi memory, 10Gi disk. No Docker. No egress beyond the forge the repository is cloned from. **Outputs.** `CATEGORY`, and the comment on the issue. **Override.** Copy to `.factory/skills/triage/`. Typical changes are your own category list and the comment format. If you change the categories, change the first rubric item's expectations with them. --- > Source: https://xavidop.github.io/kojo/docs/built-in-skills/scheduled-upkeep # Scheduled upkeep Five built-in skills are meant to run on a [schedule](/docs/schedules/): `dependency-review` applies safe dependency upgrades, `daily-digest` summarises the last day, `stale-issue-triage` goes through issues with no recent activity, `flaky-test-hunt` finds tests that fail intermittently, and `release-watch` reports upstream releases. Like any skill, each can also be run on request. "The package registries" in the kits are the ten hosts listed under [What the kits have in common](/docs/built-in-skills/#what-the-kits-have-in-common). How to change one of these skills for a repository is under [Overriding a built-in skill](/docs/built-in-skills/#overriding-a-built-in-skill). ## dependency-review Finds outdated or vulnerable dependencies, applies the safe upgrades and reports the ones that need a human decision. | | | |---|---| | Tier | `strong` | | Tools | `read_file`, `list_files`, `search`, `write_file`, `edit_file`, `exec`, `git_diff`, `memory_search`, `set_output` | | Outputs | `TEST_CMD` | | Steps per attempt | 40 (default) | **What it does.** It finds the manifests and lockfiles and the ecosystem's own tools (`go list -m -u all`, `npm outdated`, `pip list --outdated`, `cargo outdated`, and the audit command where one exists). It sorts what it finds into "apply now" (patch and minor upgrades of direct dependencies, and any upgrade that fixes a known vulnerability, when the changelog shows no breaking change for how the repository uses the package) and "needs a decision" (major versions, breaking changes in the range, build or release tooling). It applies the first group with the ecosystem's tool and never edits a lockfile by hand. It runs the build and the tests; an upgrade that breaks them is reverted and moved to "needs a decision" with the failure. It records `TEST_CMD` and finishes with a table of package, from, to and why, and the list that needs a decision. It changes dependency files only and does not rewrite application code to fit a new major version. **Goals.** ```yaml max_attempts: 2 checks: - name: tests pass after the upgrades run: ${TEST_CMD} skip_if_unset: true timeout: 30m constraints: max_changed_lines: 2000 forbidden_paths: [".github/**", ".gitlab-ci.yml", ".forgejo/**", "bitbucket-pipelines.yml", ".factory/**"] judge: rubric: | - Only dependency manifests and lockfiles changed. - No major-version upgrade was applied without being called out. - The report lists every upgrade with from and to versions, and separates what needs a human decision. ``` `TEST_CMD` is also a declared output, so an attempt that leaves it without a value is rejected whether or not the check is skipped. **Kit.** 4 CPUs, 8Gi memory, 40Gi disk. No Docker. Egress: the package registries, plus `api.osv.dev` and `vuln.go.dev`. **Outputs.** `TEST_CMD`, the upgrades in the workspace and the report. The upgrades are published as the merge policy allows. The default list of sensitive paths includes `go.mod`, `go.sum`, `package.json`, `package-lock.json`, `pnpm-lock.yaml`, `requirements.txt`, `Cargo.toml` and `Cargo.lock` at the repository root, so with the default merge policy a change to one of them is scored high risk. **Override.** Copy to `.factory/skills/dependency-review/`. Change the two groups in step 2 to your own upgrade policy. ## daily-digest Summarises the last day of activity in a repository for its maintainers. | | | |---|---| | Tier | `fast` | | Tools | `list_issues`, `list_pull_requests`, `get_issue`, `get_pr`, `memory_search` | | Outputs | none | | Steps per attempt | 40 (default) | **What it does.** It lists the issues (`list_issues`) and the pull requests (`list_pull_requests`) updated in the last 24 hours, open and closed; a merge counts as an update. It also lists the open pull requests whatever their age, to find the ones waiting for a review, and reads the issues and pull requests it needs more than a title for. It writes the digest as its final answer, in Markdown, in this order, leaving out empty sections: **Needs attention** (pull requests waiting for review for more than a day, issues that look like regressions or security reports, direct questions to a maintainer), **New**, **Done**, **Numbers** (opened, closed, merged, still open). One line per item, with its number. It does not invent activity: if nothing happened, it says so in one sentence. **Goals.** ```yaml max_attempts: 2 constraints: no_changes: true judge: model_tier: fast rubric: | - Every item names a real issue or pull request number from the listing. - The digest is ordered with what needs attention first. - It is short: one line per item. ``` **Kit.** The skill lists no sandbox tool and has no checks, so it runs without a sandbox: it reads the forge through kōjō's own tools. The kit's resources (1 CPU, 1Gi memory, 5Gi disk) are not used, and `no_changes` has nothing to check. **Outputs.** The digest, as the final report. **Override.** Copy to `.factory/skills/daily-digest/`. Change the sections and their order in step 4, and the rubric's second item with them. ## stale-issue-triage Goes through issues with no activity for a long time and says, for each, whether it is still valid, already fixed or should be closed. | | | |---|---| | Tier | `fast` | | Tools | `list_issues`, `list_pull_requests`, `get_issue`, `read_file`, `list_files`, `search`, `memory_search` | | Outputs | none | | Steps per attempt | 40 (default) | **What it does.** It reviews open issues not updated in the last 60 days, unless the request says otherwise, at most 20 per run. It lists the merged pull requests once (`list_pull_requests`, up to 100): one whose title or body names an issue ("Fixes #12") is a lead for that issue. For each issue it reads the issue and checks it against the current code, searching for the function, flag or message it names. It gives one of four verdicts: **still valid**, **likely fixed** (naming the code that now handles it, and the merged pull request when one names the issue; a pull request alone is not enough), **cannot tell** (saying what is missing) or **close** (duplicates, answered questions, reports about removed features). The result is a table of number, title, verdict and one sentence of evidence. It recommends; it does not close or comment on issues, and it has no `comment` tool. **Goals.** ```yaml max_attempts: 2 constraints: no_changes: true judge: model_tier: fast rubric: | - Every listed issue has a verdict and a sentence of evidence. - "Likely fixed" verdicts name code that exists in the repository. - No issue was closed or commented on. ``` **Kit.** 1 CPU, 2Gi memory, 10Gi disk. No Docker. No egress beyond the forge. **Outputs.** The table, as the final report. **Override.** Copy to `.factory/skills/stale-issue-triage/`. Change the 60 days and the 20 issues per run in the instructions. A schedule's `prompt` can also set a different age for one job without an override, because the instructions defer to the request. ## flaky-test-hunt Runs the test suite repeatedly to find tests that fail intermittently, and reports each with its failure rate and likely cause. | | | |---|---| | Tier | `strong` | | Tools | `read_file`, `list_files`, `search`, `exec`, `memory_search`, `memory_save` | | Outputs | none | | Steps per attempt | 40 (default) | **What it does.** It finds how the tests run, preferring the command CI uses, and runs the suite several times: at least 5 full runs, or 20 runs of a package when the request names one, using the test runner's own repeat, shuffle and race options where it has them. A test is flaky when it both passed and failed on the same code. For each it collects how many runs failed out of how many, the failure message, and whether it fails alone or only with others; then it reads the test and the code under test and names the likely cause, or "unknown". The result is a table of test, failure rate, cause and suggested fix. It saves a one-line memory per confirmed flaky test so later sessions do not mistake it for a regression. It changes no file. If nothing was flaky, it reports how many runs it did. **Goals.** ```yaml max_attempts: 1 constraints: no_changes: true judge: rubric: | - The report states how many runs were made. - Every flaky test listed has an observed failure rate from those runs. - Causes are tied to code that was read, or marked unknown. ``` With `max_attempts: 1` a rejected result is not retried; it is delivered with the critic's report. **Kit.** 8 CPUs, 16Gi memory, 40Gi disk. `needs_docker: true`. Egress: the package registries. **Outputs.** The table, and team memory entries. **Override.** Copy to `.factory/skills/flaky-test-hunt/`. Name your test command and the number of runs in the instructions, and size `resources` in the kit to your suite. ## release-watch Checks whether the libraries the repository depends on have new releases worth acting on, and summarises what changed. | | | |---|---| | Tier | `fast` | | Tools | `read_file`, `list_files`, `search`, `exec`, `memory_search`, `memory_save` | | Outputs | none | | Steps per attempt | 40 (default) | **What it does.** It reads the manifests to list the direct dependencies and their versions, and searches team memory for "release-watch" so it only reports what is new. For each direct dependency it looks up the latest release with the ecosystem's own tooling (`go list -m -versions`, `npm view versions`, `pip index versions`, `cargo search`); the sandbox can only reach the package registries. It reports a release when it is a new major version, fixes a security issue, deprecates something the repository uses, or adds something the repository works around today. Per release it gives the package, the current and new version, what changed that matters here, and where in the repository it applies. It saves one memory per reported release with the topic `release-watch`, so the next run skips it. It changes no file; upgrades are the job of `dependency-review`. If nothing is worth acting on, it says so in one sentence. **Goals.** ```yaml max_attempts: 1 constraints: no_changes: true judge: model_tier: fast rubric: | - Each reported release names the current and the new version. - Each says why it matters to this repository specifically. ``` **Kit.** 2 CPUs, 4Gi memory, 20Gi disk. No Docker. Egress: the package registries. **Outputs.** The report, and team memory entries. **Override.** Copy to `.factory/skills/release-watch/`. Change step 3 of the instructions to the kinds of release you want reported. If your dependencies come from a private registry, add its host to the kit, inside the egress limits an admin set. --- > Source: https://xavidop.github.io/kojo/docs/schedules # Schedules A schedule runs one skill on a clock: a digest every morning, a dependency review every Monday. This page covers where schedules are defined, the cron syntax kōjō accepts, exactly when a schedule fires, and how a scheduled run differs from one a person triggered.
A wall clock with orange hands, wired to a small machine under a conveyor. A wall clock with orange hands, wired to a small machine under a conveyor.
A schedule starts a skill on the clock, with nobody asking.
## Where schedules live A schedule belongs to a scope, and there are two kinds: | Scope | Defined in | Runs on | |---|---|---| | A repository | `.factory/schedules.yaml` on that repository's default branch | That repository. | | The org | The dashboard, a chat approval, or `kojo config apply` | Every enabled repository, or the ones listed in `repos`. | Both end up as the same runtime config object, `schedules`, which the scheduler reads. See [Schedules as runtime config](#schedules-as-runtime-config). No schedule exists on a new install. The org's list is seeded empty. ## schedules.yaml `.factory/schedules.yaml` holds a repository's recurring jobs. ```yaml schedules: - name: daily-digest cron: "0 8 * * 1-5" timezone: Europe/Madrid skill: daily-digest notify: C0123456789 - name: weekly-dependency-review cron: "0 9 * * 1" timezone: Europe/Madrid skill: dependency-review prompt: Apply patch and minor upgrades only. - name: flaky-tests cron: "@weekly" skill: flaky-test-hunt enabled: false ``` | Key | Type | Required | Default | Meaning | |---|---|---|---|---| | `name` | string | yes | | Identifies the schedule within its scope. Must be unique in the file. | | `cron` | string | yes | | When to run. See [Cron syntax](#cron-syntax). | | `timezone` | string | no | `UTC` | An IANA zone name such as `Europe/Madrid`. See [Time zones](#time-zones). | | `skill` | string | yes | | The skill to run. | | `prompt` | string | no | `Scheduled run of .` | Extra instruction for each run. It is the text of the request. | | `repos` | list of strings | no | every enabled repository | The repositories an org-level schedule runs on, as `forge/owner/name`. Ignored in a repository's own file. | | `notify` | string | no | | The chat channel that gets the result: a channel ID, or `surface:channel` (`mattermost:town-square`, `discord:`, `teams:`) when more than one chat surface is configured. A bare ID goes to the only configured surface. | | `enabled` | boolean | no | true | `false` keeps the schedule defined but stops it from firing. | The JSON Schema is [schedules.schema.json](/schema/schedules.schema.json); `kojo schema schedules` prints it. It checks keys and types, not cron expressions. No CLI command validates this file; kōjō validates it when it reads it. Rules the loader applies: - The document is a `schedules:` list. Unknown keys are rejected. A bare top-level list of schedules is also accepted. - `name`, `skill` and `cron` are required, names must be unique, and `cron` and `timezone` must parse. - Whether `skill` exists is not checked when the file is read. A schedule that names a skill the repository cannot resolve fires a session that fails with `skill "" is not available`. kōjō reads the file from the default branch on a push webhook for that branch and before a session of that repository starts. It copies the content into the repository's config scope as a new revision, authored `git:`. From then on the file is the owner of that scope's schedules: each sync replaces what the scope holds with what the file says. A file that was pushed before the repository was enabled is picked up at the next push to the default branch or the next session on the repository. Removing the file stops the schedules that came from it. Breaking it does not: a `schedules.yaml` that does not parse or validate changes nothing, and the schedules of the last good version keep running. The error is reported as the problem `repo/schedules.yaml` in `kojo skills list --repo `. ## Cron syntax `cron` is a five-field expression or a descriptor. The parser is [robfig/cron](https://github.com/robfig/cron) with exactly these parts enabled: minute, hour, day of month, month, day of week, descriptors. ```text ┌───────── minute 0-59 │ ┌─────── hour 0-23 │ │ ┌───── day of month 1-31 │ │ │ ┌─── month 1-12 or JAN-DEC │ │ │ │ ┌─ day of week 0-6 or SUN-SAT, 0 is Sunday │ │ │ │ │ 0 9 * * 1 ``` | Form | Example | Meaning | |---|---|---| | `*` | `* * * * *` | Every value. `?` means the same. | | List | `0 9 * * 1,3,5` | Monday, Wednesday and Friday at 09:00. | | Range | `0 8 * * 1-5` | Weekdays at 08:00. | | Step | `*/15 * * * *` | Every 15 minutes. | | Names | `0 9 1 JAN *` | 1 January at 09:00. Names are not case-sensitive. | | `@hourly` | | Minute 0 of every hour. | | `@daily`, `@midnight` | | Every day at 00:00. | | `@weekly` | | Sundays at 00:00. | | `@monthly` | | The 1st of every month at 00:00. | | `@yearly`, `@annually` | | 1 January at 00:00. | | `@every ` | `@every 6h` | A fixed interval after the last run, in Go duration syntax. | What is not accepted: - A seconds field. Six fields are an error. - `7` for Sunday. Use `0` or `SUN`. When both day of month and day of week are restricted, the schedule fires when either matches. ### Time zones Set `timezone` to an IANA name. The name is loaded from the time zone database available to the kōjō process, and an unknown name fails validation. Without `timezone`, the expression is evaluated in UTC, whatever zone the server runs in. A `CRON_TZ=` or `TZ=` prefix inside `cron` is accepted too; when it is present, `timezone` is ignored. ## When a schedule fires The scheduler runs inside `kojo serve`. This is what the code does. One tick, for one schedule: ```mermaid flowchart TD A["Tick: at start, then every 30 seconds"] --> L{"This replica gets the Postgres lock?"} L -- no --> Z["Nothing this tick: another replica fires"] L -- yes --> E{"Schedule enabled?"} E -- no --> S["Skipped, nothing recorded"] E -- yes --> K{"A last run on record?"} K -- no --> N["Now is recorded as the last run, nothing fires"] K -- yes --> D{"First cron time after the last run has come?"} D -- no --> W["Not due yet"] D -- yes --> Q["One session queued per enabled target repository"] Q --> R["Now is recorded as the last run"] ``` - **Tick.** The scheduler looks at every enabled schedule when the server starts and every 30 seconds after that. A run can start up to 30 seconds after its cron time, plus the time it waits for a free worker. - **Due.** kōjō stores the time of each schedule's last run, by scope and name. A schedule is due when the first cron time after that last run is not in the future. - **A new schedule starts from now.** The first time the scheduler sees a schedule it only records the current time. It does not fire for times before the schedule existed. - **Missed times collapse into one.** If kōjō was down, or the schedule's time passed several times since its last run, it fires once, not once per missed time. - **Disabled schedules keep their place.** While `enabled` is false nothing is recorded. If a cron time passed while the schedule was disabled, it fires at the first tick after you enable it again. - **Editing.** Changing `cron` or `timezone` keeps the last-run time; the next time is computed from it with the new expression. Renaming a schedule makes it a new schedule that starts from now. - **One session per repository.** A fire enqueues one session for each target repository. Repositories that are not enabled are skipped. - **No overlap check.** The scheduler does not look at whether the previous run of a schedule is still going. If a run takes longer than the interval, the next one is enqueued anyway and both run. - **Several replicas.** Every replica runs the loop. At each tick a replica tries to take a lock in Postgres; only the one that gets it fires, and it releases the lock when the tick ends. Each enqueued request also carries a key made of the schedule, the repository and the cron time, and the store refuses a second request with the same key. A schedule therefore fires once per cron time, however many replicas run. The last run, the session it started and the next run of every schedule are shown on the dashboard's Schedules page. ## Schedules as runtime config Schedules are runtime configuration: they are stored in Postgres as revisions, not in `kojo.yaml`, and changing them needs no restart. | Property | Value | |---|---| | Config object | `schedules` | | Scopes | `org`, and `repo:` for each repository with a `schedules.yaml` | | Content | `{"schedules": [...]}` with the keys of [schedules.yaml](#schedulesyaml) | | Role to change it | `operator` | | Takes effect | At the scheduler's next tick, on every replica | Every change is a new revision with an author and a message, and an earlier revision can be activated again. `kojo config export` includes the schedules of every scope, and `kojo config apply` loads them: ```yaml version: 1 objects: - scope: org object: schedules content: schedules: - name: weekly-dependency-review cron: "0 9 * * 1" timezone: Europe/Madrid skill: dependency-review repos: [github/acme/api] ``` Edit org-level schedules in the dashboard, or through `kojo config apply`, which needs the `admin` role. A repository with a `schedules.yaml` keeps its schedules there: an edit of its scope in kōjō opens a pull request that changes the file, and applies once it is merged ([Editing a setting that lives in git](/docs/manage/git/#editing-a-setting-that-lives-in-git)). Revisions, rollback and roles are described in [Managing kōjō](/docs/manage/). ## Create a schedule in words You can describe a schedule in natural language in chat or in the dashboard. In both places a model turns the sentence into a schedule, a person sees the result, and nothing is stored until that person confirms. ### In chat 1. Mention kōjō in a channel, or send it a direct message, with the request: "review the dependencies of github/acme/api every Monday at 9". 2. The message becomes a session. When the sender has the `operator` or `admin` role in kōjō, the orchestrator can propose a schedule with a name, a cron expression, a skill, an optional prompt and an optional repository. 3. kōjō validates the proposal: the cron expression must parse and the skill must exist. Then it posts a message in the thread titled "Create this schedule?" with the name, the cron expression, the skill, the target and **Approve** and **Deny** buttons. 4. Someone with the `operator` or `admin` role clicks a button. A click from anyone else changes nothing and the buttons stay. The first decision stands. 5. On **Approve** the schedule is added to the org's schedules as a new revision, authored by the person who approved. If the org already has a schedule with that name, the message says so and nothing is added. What a proposal in chat cannot set: `timezone` and `notify`. A schedule created this way is evaluated in UTC and reports only to the dashboard until you edit it there. Without a repository in the request it runs on every enabled repository. This works the same in Slack, Mattermost, Discord and Microsoft Teams. Setting each one up is on its page under [Surfaces](/docs/surfaces/#chat-platforms), and who may talk to kōjō is on [Who may trigger what](/docs/surfaces/triggers/). ### In the dashboard The Schedules page has a "Describe it in words" box for people with the `operator` role. 1. Type the request and submit it. The server asks the `fast` model tier to convert it into a name, a cron expression, a skill, a prompt, and a time zone if you named one. 2. The server validates the result and returns it as a proposal. Nothing is stored at this point. 3. The page opens the schedule form filled with the proposal, and with the validation error if there is one. Check each field, choose repositories and a notify channel if you want them, and confirm. 4. Confirming saves the org's schedules as a new revision. The same page adds schedules by hand and edits, disables, enables and deletes them, and shows the history of the org's list with rollback. A schedule created on this page always belongs to the org; a repository's own schedules come from its `schedules.yaml`, and editing, disabling or deleting one of them here opens a pull request that changes the file.
The Schedules page of the dashboard: a Describe it in words box with a Propose a schedule button, two schedules with their cron expression, time zone, skill, repositories, last run and next run, and the history of the org's schedule list.
The words box at the top is step 1 above; the history below it is where a change to the org's list is rolled back.
## Built-in jobs kōjō ships skills written to run on a schedule, and no schedules. Nothing recurring happens until you create a schedule. | Skill | What a run does | |---|---| | `daily-digest` | Summarises the last 24 hours of issues and pull requests. | | `dependency-review` | Applies safe dependency upgrades and reports the rest. | | `stale-issue-triage` | Gives a verdict on up to 20 open issues not updated in 60 days. | | `flaky-test-hunt` | Runs the test suite repeatedly and reports tests that fail intermittently. | | `release-watch` | Reports new upstream releases worth acting on, and remembers what it reported. | Any other skill can be scheduled too, for example `security-audit`. Each skill is described on the [Built-in skills](/docs/built-in-skills/) page. A `schedules.yaml` that turns all five on for one repository: ```yaml schedules: - name: daily-digest cron: "0 8 * * 1-5" timezone: Europe/Madrid skill: daily-digest notify: C0123456789 - name: dependency-review cron: "0 9 * * 1" timezone: Europe/Madrid skill: dependency-review - name: stale-issues cron: "0 10 1 * *" timezone: Europe/Madrid skill: stale-issue-triage notify: C0123456789 - name: flaky-tests cron: "0 2 * * 6" timezone: Europe/Madrid skill: flaky-test-hunt notify: C0123456789 - name: release-watch cron: "0 9 * * 3" timezone: Europe/Madrid skill: release-watch notify: C0123456789 ``` The times are examples. Replace the channel ID with one of yours. ## How a scheduled run differs A scheduled run is an ordinary session. These are the differences from a session someone triggered with a mention, a chat message or `kojo run`. | | Scheduled run | Triggered run | |---|---|---| | Surface and kind | `schedule` | The forge, a chat surface (`slack`, `mattermost`, `discord`, `teams`), `cli`, `dashboard` or `mcp`. | | Runs as | `schedule:/` | The person who asked. | | May write | Always. | Only when that person has the permission or role for it. | | Chooses skills | No. Exactly the schedule's `skill` runs, once. | The orchestrator chooses, unless a skill was named. | | Issue or pull request | None. | The one the request is about, if any. | **Who it runs as.** There is no person behind a scheduled run, so no forge permission is checked when it fires. The run is trusted to write because of who can create schedules: someone with the `operator` role for the org's list, or someone who can get a commit onto the default branch for a repository's `schedules.yaml`. Treat changes to that file as changes to what kōjō may do unattended. **No orchestrator.** The skill runs directly with the schedule's `prompt` as its task, and its result goes to the goal critic as usual. A scheduled `fix-bug`, for example, gets no `reproduce-bug` step before it. **No issue to comment on.** The `comment` tool returns an error in a scheduled run, because the session is not about an issue or pull request. A skill's final report is its result. **Where the result goes.** With `notify`, the result is posted to that channel as a new message. Without it, the result is only on the session: open it on the dashboard's Sessions page, filtered by the surface `schedule`, or with `kojo sessions show`. **Budgets.** There is no separate budget for schedules. Each scheduled session has the same per-session cap as any other and counts toward the same daily cap. An org-level schedule without `repos` starts one session per enabled repository at the same moment; size the daily cap with that in mind. While the daily cap is spent, a scheduled session that has not started waits in the queue and is looked at again every 10 minutes; the cap is a sum over the last 24 hours, so it runs once enough earlier spend has aged out. See [Models](/docs/models/). **Merge policy.** A scheduled run that changes code goes through the repository's merge policy like any other change, and the pull request it opens is titled `Scheduled: `. What differs is whether there is somewhere to ask a human: | Policy mode | With `notify` | Without `notify` | |---|---|---| | `draft_only` | Draft pull request. | Draft pull request. | | `ask` | Approval buttons are posted in the notify channel. | Draft pull request, because there is no thread to ask in. | | `auto_merge`, low risk | Merges once required checks are green. | The same. | | `auto_merge`, medium risk | Asks in the notify channel before merging. | A pull request ready for review, not merged. | | `auto_merge`, high risk | Draft pull request. | Draft pull request. | The `auto_merge` rows apply when an admin allowed auto-merge for the repository and its base branch is protected with required checks. Without the first, the mode is treated as `ask`; without the second, the change is a draft pull request. A result the goal critic rejected is always published as a draft with its report. The modes and the risk score are explained on the [Merge policy](/docs/merge-policy/) page. --- > Source: https://xavidop.github.io/kojo/docs/evals # Evals An eval runs a skill against small fixture repositories and reports how many results the goal critic accepted. An eval [from your own history](#evals-from-your-own-history) runs it instead on issues one of your repositories already fixed, judged by the tests the fix added. This page is for people who change skills, add fixtures, decide whether an eval is required before a skill goes live, or want to know how kōjō does on their code before turning it on.
Three identical parcels pass under a measuring arch next to a meter with an orange needle. Three identical parcels pass under a measuring arch next to a meter with an orange needle.
An eval puts the same small cases through a skill and reads off how many results the goal critic accepts.
## What an eval measures A case is a small repository with a seeded problem (a bug, a missing feature, a flaky test, an outdated dependency), plus a task. A case for a skill that reads issues and pull requests also seeds them, on an in-memory forge of its own. The skill runs on it as a dry run in a throwaway sandbox, with its real `goals.yaml` and `kit.yaml`. The case passes when the goal critic accepts the result. Nothing is pushed or posted. An eval reports, per case, whether it passed, how many attempts the critic needed, what it cost, and how close the diff is to a reference fix when the fixture has one. ## Run an eval ```sh kojo eval fix-bug ``` `kojo eval` takes one skill name, or `--all` for every skill that has fixtures. Naming neither, or both, is a usage error. | Flag | Default | Meaning | |---|---|---| | `--all` | false | Evaluate every skill that has fixtures. With `--factory`, every skill that has cases in that directory's `evals/`. | | `--local` | false | Run in this process from `kojo.yaml`, with an in-memory store. | | `--factory` | | With `--local`: also read skills and eval cases from a repository's `.factory` directory. See [A repository's own skills](#a-repositorys-own-skills). | | `--json` | false | Print one JSON document when the command ends, instead of text. See [Output](#output). Not with `--history`. | | `--min-pass-rate` | the activation policy's minimum | Fail below this pass rate, from 0 to 1. Without the flag, the command reads `min_eval_pass_rate` from the server's [activation policy](#the-activation-gate). With `--local` it takes `seed.activation.min_eval_pass_rate` from the file. Both are 0 unless someone set them. | The global flags (`--server`, `--token`, `-f`) are in the [CLI reference](/docs/cli/). ### On the server Without `--local` the command asks the server named by `--server` to run the eval and polls it every two seconds until it ends. Starting an eval needs a token with the `skill:edit` role or higher. The server runs the cases with its own workers, sandbox driver and models. Each case is an ordinary session with the surface `eval`, so you can open it in the dashboard and replay it. The run is stored and listed on the dashboard's Evals page, which can also start an eval of a skill's active version.
The Evals page of the dashboard: five eval runs with their status, pass rate, cost, who ran them and when, two of them on the history of a repository, and one fixture run of fix-bug open with its four cases, three passed and one failed, each with attempts, cost and similarity to the human fix.
A stored run, opened case by case; the failed case names the check the critic ran.
### In this process With `--local` the command builds kōjō from the `kojo.yaml` named by `-f`, with an in-memory store and without forges or chat, runs the cases and exits. A case that needs issues or pull requests brings them on its own in-memory forge ([Issues and pull requests](#issues-and-pull-requests)). Nothing is stored. The sandbox driver and the models are the ones that file configures, so the file must name a driver that runs commands. The `fake` driver does not: every case fails on it while the fixture is being seeded. The repository has a config for this, [evals/kojo.eval.yaml](https://github.com/xavidop/kojo/blob/main/evals/kojo.eval.yaml). It uses the `mock` model provider replaying the recorded responses and the development-only `docker` driver, and it sets the minimum pass rate to 1. It needs Docker and no keys. Run it from the repository root: ```sh kojo eval --all --local -f evals/kojo.eval.yaml ``` This is what `make eval` and CI run; see [Replaying the evals](#replaying-the-evals). ### A repository's own skills With `--local`, `--factory` names a repository's `.factory` directory, and the command reads two things from it. Its `skills//` are loaded as the server loads a repository's skills, and come before the built-in skill of the same name. Its `evals///` are cases in the layout of [Fixtures](#fixtures): a skill with a directory there is evaluated on those cases alone, and every other skill keeps its built-in fixtures. With `--all` the command evaluates the skills that have cases in `evals/`. ```sh kojo eval changelog-entry --local -f kojo.ci.yaml --factory .factory ``` A skill of `skills/` that does not load, or that the server would drop because its kit asks for more than the egress limits of `settings/egress` allow, stops the command with exit 1 and the reason, instead of the built-in skill of its name running in its place. Files are read from disk, with their executable bit, and a symbolic link that leads out of the directory is not followed. The [Skills CI](/docs/skills/ci/) GitHub Action runs this on each pull request that changes a skill, and comments the pass rate, cost and cases on it. ### Which version of the skill runs An eval session has no repository, so the skill is resolved from the org layer and the built-in layer only: the org's version when the org overrides the skill, otherwise the built-in one. A repository's own `.factory/skills/` override is not what the server's eval runs. To evaluate an unpublished change on the server, run the eval from its draft in the Skills studio; see [the activation gate](#the-activation-gate). With `--local --factory`, the repository's own skills come first; see [A repository's own skills](#a-repositorys-own-skills). ### Output One summary line per skill, then one line per case. This is the replay run with `evals/kojo.eval.yaml`: ```text build-feature: 100% passed (1 case(s), $0.00) pass shout-flag 1 attempt(s) $0.00 similarity - daily-digest: 100% passed (1 case(s), $0.00) pass one-day 1 attempt(s) $0.00 similarity - dependency-review: 100% passed (1 case(s), $0.00) pass mirror-upgrades 1 attempt(s) $0.00 similarity 100% fix-bug: 100% passed (1 case(s), $0.00) pass last-page 1 attempt(s) $0.00 similarity 100% flaky-test-hunt: 100% passed (1 case(s), $0.00) pass shared-scratch 1 attempt(s) $0.00 similarity - port-sdk: 100% passed (1 case(s), $0.00) pass truncate 1 attempt(s) $0.00 similarity - release-watch: 100% passed (1 case(s), $0.00) pass upstream-releases 1 attempt(s) $0.00 similarity - reproduce-bug: 100% passed (1 case(s), $0.00) pass slug-digits 1 attempt(s) $0.00 similarity 100% review-pr: 100% passed (1 case(s), $0.00) pass prune-keep 1 attempt(s) $0.00 similarity - security-audit: 100% passed (1 case(s), $0.00) pass command-injection 1 attempt(s) $0.00 similarity - stale-issue-triage: 100% passed (1 case(s), $0.00) pass old-issues 1 attempt(s) $0.00 similarity - triage: 100% passed (1 case(s), $0.00) pass last-row 1 attempt(s) $0.00 similarity - ``` | Column | Meaning | |---|---| | `pass` or `FAIL` | Whether the goal critic accepted the case. | | name | The case's directory name. | | attempts | How many verdicts the critic gave. | | cost | What the case's session spent, from the prices configured for the tiers. | | similarity | Diff similarity to the reference fix, or `-` when the fixture has none. | | detail | For a failed case: the session's error or the critic's report, cut at 100 characters. | With `--json` the command prints no text: when it ends, it prints one JSON document to standard output, also when it fails. The logs of `--local` stay on standard error. ```json { "min_pass_rate": 1, "passed": true, "runs": [ { "id": "evl_01m8yf9ffvhjqfpmpj0t7vt8je", "skill": "changelog-entry", "models": "fast=mock/replay strong=mock/replay", "cases": [ { "name": "fixed-timeout", "passed": true, "attempts": 1, "cost_usd": 0, "session_id": "ses_01m8yf9ffvhjqfpmpj0xxrgxss", "similarity": 1 }, { "name": "new-feature", "passed": true, "attempts": 1, "cost_usd": 0, "session_id": "ses_01m8yf9j5vteeb70kc8fj8bsst", "similarity": -1 } ], "pass_rate": 1, "cost_usd": 0, "status": "done", "author": "cli", "started_at": "2026-12-03T17:30:02.107567Z", "ended_at": "2026-12-03T17:30:06.610613Z" } ] } ``` | Key | Meaning | |---|---| | `min_pass_rate` | The pass rate each skill was held to. | | `passed` | `true` when every run finished at or above it. The exit code says the same. | | `runs` | One eval run per skill evaluated, as the API returns it: its cases with `passed`, `attempts`, `cost_usd`, `similarity` (-1 without a reference fix), `detail` for a failed case and `session_id`; `pass_rate`, `cost_usd`, `models` and `status`. | | `error` | Why the command failed, when it did: a skill below the bar, or an eval that could not start or finish. The runs that finished are still listed. | A usage error in the flags prints no JSON, only the message on standard error, with exit code 2. Everything after that, a `kojo.yaml` that does not load included, is in `error`, with the exit code of [Exit codes](#exit-codes). ### Exit codes | Code | When | |---|---| | 0 | Every evaluated skill reached `--min-pass-rate` and every run finished. | | 1 | A skill is below `--min-pass-rate`, a run did not finish, or the eval could not start, for example because the skill has no fixtures. | | 2 | Usage error, or `kojo.yaml` does not load. | | 3 | The server cannot be reached or answered with a server error. With `--local`: kōjō could not be started from the file. | When the minimum is 0, which it is until the activation policy or the seed sets one, a run in which every case fails still exits 0. Pass `--min-pass-rate` when you use the exit code as a gate and are not sure the policy sets one. ## Fixtures Fixtures are compiled into the binary from [evals/fixtures](https://github.com/xavidop/kojo/blob/main/evals/embed.go). A server evaluates against the fixtures of the version it runs; adding a case means rebuilding. A repository's own cases, in the same layout, are read from disk by `kojo eval --local --factory`; see [A repository's own skills](#a-repositorys-own-skills). ```text evals/fixtures/ └── fix-bug/ # the skill's name └── last-page/ # the case's name ├── case.yaml # required ├── reference.patch # optional └── repo/ # required: the repository the skill works on ├── AGENTS.md ├── lib/pages.sh └── tests/pages_test.sh ``` | Path | Required | Content | |---|---|---| | `case.yaml` | yes | The task and the inputs. | | `repo/` | yes | The files of the repository, copied into the sandbox's workspace. | | `reference.patch` | no | The human fix as a unified diff. Only used for the similarity score. | | `references/` | no | [Reference repositories](/docs/skills/reference-repositories/#in-an-eval-fixture) the skill reads next to the workspace: one directory per reference, with an optional `.diff` and `.md` beside it. `port-sdk` needs one named `source`. | | a diff file | no | The diff of a seeded pull request, named by its `diff` key in `case.yaml`, such as `pr-42.diff`. | `case.yaml` has these keys: | Key | Type | Required | Meaning | |---|---|---|---| | `task` | string | yes, unless `number` is set | What the skill is asked to do. It is the text of the request. With `number` and no `task`, the task is the title and body of that issue or pull request, as a forge event would bring them. | | `inputs` | map of string to string | no | Values handed to the skill as an earlier skill would have recorded them. Names starting with `KOJO_` are reserved. | | `number` | integer | no | The issue or pull request the request is about. `forge` must seed it. The request is about a pull request when it is seeded as one. | | `forge` | object | no | The issues and pull requests the skill reads. See [Issues and pull requests](#issues-and-pull-requests). | This is the case of the `fix-bug` fixture: ```yaml task: | Bug report: `pages` reports one page too few whenever the items do not fill the last page. `sh lib/pages.sh 10 3` prints 3, but 10 items at 3 per page need 4 pages. A reproduction test exists: tests/pages_test.sh. inputs: REPRO_TEST: tests/pages_test.sh REPRO_CMD: sh tests/pages_test.sh ``` The inputs stand in for a `reproduce-bug` run: they give `fix-bug` its `${REPRO_CMD}` check and its `${REPRO_TEST}` constraint. ### Issues and pull requests `triage`, `review-pr`, `daily-digest` and `stale-issue-triage` read the forge: an issue and its comments, a list of issues or of pull requests, a pull request and its diff. An eval session has no repository on a forge, so a case seeds what the skill reads under `forge`. The session's `get_issue`, `list_issues`, `list_pull_requests`, `get_pr`, `get_pr_diff` and `comment` then work on an in-memory forge that holds it, with the repository `/` on a forge called `fixture`. A new one is built when the session first uses a forge tool. This is the `review-pr` case, whose request is pull request #42: ```yaml number: 42 forge: pull_requests: - number: 42 title: "prune: make the number of backups to keep configurable" author: jlee head: prune-keep opened: 5h diff: pr-42.diff body: | The small hosts run out of disk with 7 backups, so this adds `--keep N` to `bin/prune.sh`. Without the flag nothing changes: the default stays 7. ``` Its `repo/` is the pull request's head, so the code the subagent reads and runs is the code under review, and `pr-42.diff` is what `get_pr_diff` returns. The workspace of a case whose `number` is a pull request with a `diff` gets two commits: the base, which is the diff applied in reverse to `repo/`, and `repo/` itself as the pull request's head on top of it. `KOJO_PR_BASE` then names the base, and a check with [`on_base`](/docs/skills/goals/#checks-against-the-code-from-before-the-pull-request) runs on it. So for a skill with an `on_base` check the diff must apply in reverse to `repo/`: a case whose diff does not fails at once, with an error that names the case. A case of any other skill whose diff does not apply runs on `repo/` alone, with no base commit. Write the diff with `git diff` between the base and `repo/` rather than by hand. An issue under `forge.issues`: | Key | Default | Meaning | |---|---|---| | `number` | required | Above 0. Issues and pull requests share numbers, so no two may have the same. | | `title` | required | | | `body` | empty | | | `author` | `alice` | | | `labels` | none | | | `state` | `open` | `open` or `closed`. | | `opened` | now | How long ago it was opened. | | `comments` | none | Oldest first, each with `author` (default `alice`), `body` and `age`. | A pull request under `forge.pull_requests` has the same `number`, `title`, `body`, `author`, `opened` and `comments`, and: | Key | Default | Meaning | |---|---|---| | `state` | `open` | `open`, `closed` or `merged`. | | `closed` | now | How long ago a `closed` or `merged` pull request was closed or merged. No earlier than `opened`. | | `draft` | false | | | `head` | `patch-` | The branch `get_pr` reports. | | `base` | `main` | The branch it targets. | | `diff` | none | A file of the case directory holding the unified diff `get_pr_diff` returns. Without one the diff is empty. | Times are ages, counted back from when the forge is built: a Go duration (`90m`, `36h`) or a number of days (`14d`). An issue was last updated by its last comment, or when it was opened if it has none; a pull request by its last comment or when it was closed or merged, whichever is later, so `list_issues` and `list_pull_requests` with `since_hours` see what a real forge would. A comment may not be older than what comes before it. As on GitHub, GitLab and Forgejo, `list_issues` leaves pull requests out: a skill finds them with `list_pull_requests`. A value with ` #` in it, such as `body: Fixes #12.`, needs quotes: unquoted, YAML reads ` #` as the start of a comment and the value stops before it. The forge is only read. `comment` records the comment without posting it, as in any dry run, and nothing else writes to it. `kojo eval` checks a case's `forge` section when it loads the case: a duplicate number, an unknown state, comments out of order, a `closed` age on an open pull request or before its opening, a missing diff file or a `number` that is not seeded is an error that names the case. ### The fixtures shipped in this version Every built-in skill has at least one case: | Skill | Case | What it holds | Reference fix | |---|---|---|---| | `fix-bug` | `last-page` | A page count that rounds down, with a failing test. | yes | | `build-feature` | `shout-flag` | A greeting command that needs a `--shout` flag, a test and a README entry. | no | | `security-audit` | `command-injection` | A backup script that runs a request parameter through `eval`. | no | | `port-sdk` | `truncate` | A shell implementation of a small text library that must gain the `truncate` function its Python sibling gained; the Python source is a reference repository. | no | | `reproduce-bug` | `slug-digits` | A slug command that drops digits although its README says it keeps them. The reproduction must fail on that, and only test files may change. | yes | | `triage` | `last-row` | Issue #31: a CSV sum that misses the last row, caused by a `while read` loop that skips a final line without a newline. #27 reports the same behaviour; #29 only looks similar. | no | | `review-pr` | `prune-keep` | Pull request #42, which makes the number of kept backups configurable with an off-by-one: the default keeps 6 instead of 7 and `--keep 1` deletes every backup, while its tests pass. | no | | `dependency-review` | `mirror-upgrades` | Three dependencies from a registry copy in the repository (`mirror/`): a security advisory and a patch release to apply, and a new major that renames functions the code calls. Applying the major fails the tests, and a lockfile edited by hand fails them too. | yes | | `release-watch` | `upstream-releases` | Dependencies from a registry copy in the repository, with release notes: a minor that adds what the code works around and deprecates a function it calls, a new major that removes it, a deprecation in another package, and a patch that does not matter here. | no | | `flaky-test-hunt` | `shared-scratch` | A suite run in an order drawn from `SEED`, where one test fails whenever another left keys in the scratch directory they share: 6 of seeds 1 to 10, never alone. | no | | `daily-digest` | `one-day` | A day on the forge: three new issues (a regression and a direct question among them), one closed by a merged pull request, and a pull request waiting three days for review, named in a comment. Older issues stay out. | no | | `stale-issue-triage` | `old-issues` | Five stale issues, one per verdict (likely fixed, still valid, cannot tell, and two to close), checked against the code, and two recent ones that are not stale. | no | | `write-tests` | `unique-flag` | Pull request #12, which adds `--unique` to a line counter without a test. Tests of `--unique` must pass on its head and fail on the code from before it. | no | | `write-tests` | `refactor` | Pull request #13, which moves a rounding into a helper and changes no behaviour. The tests pass, `NEW_TESTS_CMD` stays unset, and the report says why behaviour is unchanged. | no | | `docs-sync` | `renamed-flag` | Pull request #21, which renames `--dry` to `--dry-run` and leaves `README.md` and `docs/usage.md` naming the old flag. The docs check (`DOCS_CHECK_CMD`) refuses the old name, and `CHANGELOG.md`, which names it too, must not change. | no | | `docs-sync` | `nothing-to-update` | Pull request #22, which changes how files are copied and nothing a reader sees. Nothing changes, and the report says what was searched. | no | Fixtures run offline. The `dependency-review` and `release-watch` cases cannot reach a package registry, so their repository keeps one: `mirror/` holds every published version, the release notes and the advisories, and `tools/deps.sh` is the package tool that reads it. Their AGENTS.md says so. The skills' own commands for real ecosystems (`npm outdated`, `go list -m -u all`) are not exercised by them. `kojo eval` on a skill without fixtures, such as one you created, fails with `skill has no fixtures`. ## How a case is run and scored 1. The runner submits one request per case: the skill named directly, the case's `task` as its text, `dry_run` set, the case's `inputs`, its `number` when it has one, and the title `Eval: /`. 2. The engine runs it like any session that names a skill. There is no orchestrator turn. It creates the sandbox the skill's kit asks for. 3. Instead of cloning, the workspace is filled from the fixture's `repo/` directory and committed as one commit. Diffs are measured from that commit. The fixture's `AGENTS.md` is used as the repository's. 4. The subagent works and the goal critic checks each attempt, exactly as in a real session: declared outputs, constraints, checks, then the judge. See [goals.yaml](/docs/skills/goals/#how-the-goal-critic-uses-it). 5. Because it is a dry run, nothing is pushed, `comment` records without posting, and `memory_save` stores nothing. The diff is kept on the session's result. 6. Cases run one after another. A case that has not ended after 30 minutes is cancelled and counted as failed. The scores: | Score | How it is computed | |---|---| | Passed | The session ended as succeeded and the goal critic accepted the result. | | Attempts | The number of critic verdicts in the session. | | Cost | The session's model spend in USD. | | Similarity | The lines the run's diff adds and removes, compared with those of `reference.patch`: lines in common divided by lines in either (Jaccard), 0 to 1. Whitespace at the ends of a line is ignored. | | Pass rate | Passed cases divided by all cases of the skill. | Similarity is reported and never decides whether a case passes. Two things follow from an eval session having no forge repository: - `get_issue`, `list_issues`, `list_pull_requests`, `get_pr`, `get_pr_diff` and `comment` work on the case's own forge when it seeds one ([Issues and pull requests](#issues-and-pull-requests)), and return an error otherwise. Everything else the skill needs goes into `task` and `repo/`. - The model [budgets](/docs/models/) apply as to any session, and eval spend counts toward the daily cap. While the daily cap is spent, a case that has not started waits; it is cancelled like any other case if that takes it past 30 minutes. An eval session is a dry run, and dry runs are not retried after a transient failure: the case fails with that error. ## Evals from your own history Fixtures say how a skill does on cases written for it. An eval from history says how it does on your code: it takes pull requests that fixed an issue in one of your repositories, gives the skill each issue at the commit before the fix, and judges the result with the tests the fix added, which the skill never sees. Recordings cannot replay arbitrary history, so these evals run live models and cost what the calls cost. Nothing is pushed or posted. ```sh kojo eval fix-bug --history github/acme/api --test-cmd 'go test ./...' --limit 10 --validate-only kojo eval fix-bug --history github/acme/api --test-cmd 'go test ./...' --limit 10 ``` The skill must change code (`fix-bug` and `build-feature` have the same shape: an issue in, a change out), and the repository must be enabled. It is resolved as that repository's sessions resolve it today. The run is on the server, with its workers, sandbox driver and models; `--local` does not apply. | Flag | Default | Meaning | |---|---|---| | `--history` | | The repository, as `forge/owner/name`. | | `--test-cmd` | required | The shell command that runs the repository's tests, from the repository root. | | `--limit` | required | The most cases to take, 1 to 50. | | `--since` | 90 days ago | Only pull requests merged since this date (`2026-06-01`) or this many days (`30d`). | | `--validate-only` | false | Mine and check the cases, report the cost bound, run no model. | | `--yes`, `-y` | false | Run the valid cases without asking. | | `--min-pass-rate` | none | Exit 1 below this pass rate. | ### What becomes a case The runner lists the pull requests merged since `--since`, newest merge first, looks at no more than 300, and keeps one as a case when: - its description closes exactly one issue of the repository with the forge's closing keywords: `close`, `closes`, `closed`, `fix`, `fixes`, `fixed`, `resolve`, `resolves` or `resolved`, then `#12`, `owner/name#12` or the issue's URL. On GitLab the `-ing` forms, `implement` and lists such as `Closes #1, #2 and #3` count too. A pull request that closes no issue, two issues, or an issue of another repository is left out, and so is a second fix of an issue that is already a case; - it changes at least one test file and at least one other file; - the forge reports the commit it was merged as. It stops at `--limit` cases. Every pull request it leaves out is listed with the reason. A file is a test when it is under a directory named `test`, `tests`, `__tests__`, `spec`, `specs`, `testdata`, `e2e`, `__snapshots__` or `__mocks__` (and a few more), or when it is named as the common languages name tests: `*_test.go`, `test_*.py`, `*_test.py`, `conftest.py`, `*.test.ts`, `*.spec.js` and the other JavaScript and TypeScript extensions, `*_spec.rb`, `*Test.java`, `*Tests.kt`, `*Tests.cs`, `*Tests.swift`, `*_test.dart`, `*_test.exs`, `*_test.cc`, `*.bats`, `*.t`. Tests that live inside a source file, such as Rust's `#[cfg(test)]` modules, count as code. The rules are in [internal/testpaths/testpaths.go](https://github.com/xavidop/kojo/blob/main/internal/testpaths/testpaths.go). ### Checking each case, without a model Each case is checked by a session that calls no model. In a sandbox of the skill's image, after its kit setup, it fetches the fix and finds the commit before it: | The fix landed as | The commit before it | |---|---| | A merge commit | Its first parent. | | One commit that changes exactly the pull request's files (a squash, or a rebase of one commit) | Its parent. | | Several commits (a rebase) | The pull request's base, as the forge reports it. | Then it runs the test command twice on that commit: with only the fix's test files written in, the command must fail; with the whole fix, it must pass. A case that does not hold is invalid, with the reason, and costs no model call: - the fix's tests pass without the fix; - the fix's tests do not pass with the whole fix; - the commit before the fix already has its change; - the fix changes no test file against the commit before it; - the check could not run (the commit is gone from the forge, the sandbox failed). The test command is your input, never a model's. It runs only in sandboxes, as a shell script from the repository root, for at most 30 minutes a run. `KOJO_HIDDEN_TESTS` holds the fix's test files, one per line, so the command can target them: ```sh go test $(dirname $KOJO_HIDDEN_TESTS | sort -u | sed 's|^|./|') ``` ### The cost bound and the confirmation Once every case is checked, the run waits as `validated` and reports how many cases are valid and the most running them can cost: the valid cases times the per-session budget (`budgets.per_session_usd` of `settings/models`, see [Models](/docs/models/)). A session checks its budget before each model call, so its last call can take it over by what that call costs. Without a per-session budget, or when a tier the skill uses (its own, and its judge's) has no price, nothing bounds the cost: the run says so and cannot be confirmed. Nothing calls a model until someone confirms. `kojo eval` asks, and `--yes` answers for you; without an answer and without `--yes` it exits 2 and the run stays validated. In the dashboard the run shows a button. Through the API or MCP the confirmation carries the bound you were shown, and nothing starts when the bound is now higher. A confirmation is refused while the [daily budget](/docs/models/) is spent; once the cases run, a case that would start after it is spent is skipped with that reason. The cases run as many at a time as the server has workers (`server.workers`). ### What the skill cannot see The number means something only if the skill cannot find the fix. In the skill's session: - The workspace is fetched at the commit before the fix and nothing else: no tags, no remote, no `FETCH_HEAD`. Every commit in it is that commit or one of its ancestors. - The forge is reachable only while the core fetches. Every other sandbox policy of the session leaves out the forge's host and its subdomains (for GitHub also `githubusercontent.com`) and its credential, even when the kit allows them. Package registries the kit allows stay reachable: a repository that publishes itself as a package (a Go module through `proxy.golang.org`, an npm package) can be downloaded from there at a later version, and that is not blocked. - The forge tools (`get_issue`, `list_issues`, `list_pull_requests`, `get_pr`, `get_pr_diff`) see the repository as it was when the fix's pull request was opened: nothing created at or after that moment, never the fix's pull request, and the issue still open. The task is the issue's title and body as they are today. A pull request merged after that moment is shown open, without its diff. The state of another issue is the one it has today. `comment` records without posting. - Team memory saved at or after that moment is not searched, and the repository's `AGENTS.md` and `.factory/memory/` are read from the workspace, not from the default branch. ### How a case is scored When the skill's session ends, a second check session fetches the commit before the fix and the fix, applies the session's diff to that commit (only the change carries over, not whatever else the skill's sandbox held), writes the fix's version of its test files over it, removing those the fix removed, and runs the test command. The case passes when it exits 0. | Recorded | Meaning | |---|---| | State | `pass`, `fail`, `invalid` with the reason, `error` (a session or a check failed for a reason of its own) or `skipped` (the daily budget was spent). | | Goal critic | Whether the critic accepted the skill's result, as in a real session. It can accept a change the fix's tests reject. | | Similarity | The non-test lines the change adds and removes, compared with the fix's (the [similarity](#how-a-case-is-run-and-scored) of fixture evals). | | Cost, took | The skill's session's model spend and duration. Check sessions cost nothing. | | Sessions | The skill's session, the scoring check and the validation check, each replayable in the dashboard. | | Pass rate | Passed cases divided by the cases that ran (`pass`, `fail`, `error`). Invalid and skipped cases do not count. | A history eval does not count for the [activation gate](#the-activation-gate): it measures the skill in use on one repository. ```text fix-bug on the history of github/acme/api: 5 merged pull request(s) looked at, 3 case(s), 2 skipped skipped #404 its description closes no issue skipped #390 it changes no test file PASS issue #412 fix #419 critic accepted similarity 71% $1.84 FAIL issue #398 fix #403 critic accepted similarity 22% $2.61 the fix's tests fail on the result (exit 1) INVALID issue #361 fix #364 critic - similarity - - the fix's tests pass without the fix 50% passed the fix's tests; cost $4.45 ``` `kojo eval --history` exits 1 when no case is valid, when the run does not finish, or below an explicit `--min-pass-rate`; 2 for a usage error or a cost that cannot be bounded.
An eval of fix-bug on the history of github/acme/api open on the Evals page: 14 merged pull requests looked at, 4 valid cases and 2 invalid, a pass rate of 50 percent, then each case with its issue, its fix, the goal critic's verdict, similarity, cost, time and links to its sessions; two invalid cases give their reason.
A history eval that ran: the critic accepted the second case, the fix's tests did not.
## Recordings The model provider `mock` does not call a model. It replays recorded responses from the directory `models.recordings` names, with no network and no keys. The dev stacks, the end-to-end tests and the eval test in `make test` run on it. The provider itself is described on the [Models](/docs/models/) page. Replay only replaces the model. The tool calls a recording contains are executed for real in the sandbox, and the skill's checks really run. A replayed eval therefore tests the engine, the skill's goals and the fixture, not the quality of a model. ### Format Every `.yaml` or `.yml` file under the recordings directory, at any depth, is a list of recordings. The eval recordings are in [testdata/recordings/evals](https://github.com/xavidop/kojo/blob/main/testdata/recordings/evals/fix-bug.yaml), one file per skill. This is the one for `fix-bug`: ```yaml - purpose: subagent:fix-bug match: "lib/pages.sh" turns: - tool_calls: - { name: read_file, input: { path: lib/pages.sh } } - { name: read_file, input: { path: tests/pages_test.sh } } - text: "The page count is an integer division, which rounds down. It has to round up." tool_calls: - name: edit_file input: path: lib/pages.sh old_string: "echo $(( total / size ))" new_string: "echo $(( (total + size - 1) / size ))" - { name: set_output, input: { name: TEST_CMD, value: "sh tests/pages_test.sh" } } - tool_calls: - { name: exec, input: { command: "sh tests/pages_test.sh" } } - text: | Root cause: `pages` divided total by size with integer division, which rounds down, so a partly filled last page was not counted. Change: the division now rounds up (`(total + size - 1) / size`) in lib/pages.sh. Zero items still give zero pages. The reproduction test and the rest of tests/pages_test.sh pass; the test file is unchanged. - purpose: judge:fix-bug match: "lib/pages.sh" turns: - json: { pass: true, unmet: [], feedback: "" } ``` | Key | Meaning | |---|---| | `purpose` | Who is calling: `subagent:`, `judge:`, `orchestrator`, `risk`. A trailing `*` matches any suffix, as in `judge:*`. | | `match` | Optional. A string that must occur in the system prompt or the user messages. Recordings with a `match` are tried before those without. | | `turns` | The replies, in order. | | `turns[].text` | The model's text. | | `turns[].tool_calls` | Tool calls, each with `name` and `input`. | | `turns[].json` | A structured answer, such as a judge's verdict. | | `turns[].tokens_in`, `turns[].tokens_out` | Token counts to report. Default 100 and 20. | | `repeat_last` | Answer with the last turn once the turns are used up, instead of failing. Default false. | The reply given is the turn whose index equals the number of model messages already in the conversation. Replay is stateless, so a session resumed from a checkpoint gets the same answers. When no recording fits, the session fails with `mock model: no recording for purpose ...`, and it is not retried. ### Replaying the evals The eval test replays every fixture against the recordings, on a sandbox driver for tests that runs the commands in a temporary directory on the host. It needs `git` and nothing else: ```sh go test ./internal/eval/ -run TestBuiltinSkillEvals ``` It requires every case to pass on the first attempt, and the `fix-bug` diff to have a similarity of 1 to the reference fix. `make test` includes it. `make eval` builds the binary and runs `kojo eval --all --local -f evals/kojo.eval.yaml`: every fixture, in the kōjō process, with the recorded responses. Unlike the Go test it uses real sandboxes, plain containers on the `docker` driver, so it needs Docker. It exits 1 when a skill is below a pass rate of 1. CI runs it on every change. ```sh make eval make eval SKILL=fix-bug ``` | Variable | Default | Meaning | |---|---|---| | `SKILL` | empty | Evaluate this one skill instead of `--all`. | | `EVAL_CONFIG` | `evals/kojo.eval.yaml` | The config file passed with `-f`. | | `EVAL_ARGS` | empty | More flags for `kojo eval`, passed as they are. | ### Live models and recording Two environment variables change what a recordings setup does: | Variable | Effect | |---|---| | `KOJO_LIVE_MODELS=1` | Ignore `models.recordings` and call the providers of the configured tiers. It has no effect when a tier's provider is `mock`. | | `KOJO_RECORD=1` | With live models and `models.recordings` set, write every model response under `/recorded/`, one file per session and purpose. | `make record` uses both to make new recordings of the evals with a live model: ```sh make record make record SKILL=fix-bug ``` It needs `ANTHROPIC_API_KEY` in the environment and refuses to start without it; the calls cost what the model costs. It builds the binary and runs `kojo eval --all --local --min-pass-rate 0` with [evals/kojo.record.yaml](https://github.com/xavidop/kojo/blob/main/evals/kojo.record.yaml), which is the eval config with real model tiers and `models.recordings` set to `out/recordings/evals`. The answers are written under `out/recordings/evals/recorded/`. Nothing replays them from there. To use a recorded file: 1. Read it. A recording holds what the model said, including tool calls; make sure no key or token is in it. 2. Add a `match` that is specific to the case. A recorded file holds a `purpose` and its `turns`, without a `match`. 3. Move it into the skill's file under `testdata/recordings/evals/`, which is what the replay runs read. The same record config runs the evals against a live model without recording, which is what the nightly CI job does: ```sh KOJO_LIVE_MODELS=1 make eval EVAL_CONFIG=evals/kojo.record.yaml ``` ## Write a new case 1. **Choose the skill and a name.** Create `evals/fixtures///`. The case name is the directory name. 2. **Build `repo/`.** Make the smallest repository that shows the problem. Add an `AGENTS.md` that says how to run the tests, as the shipped fixtures do. Keep it to plain POSIX shell so it runs in any sandbox image, and call scripts with `sh path/to/script.sh`: the executable bit of a fixture file is not preserved. 3. **Write `case.yaml`.** Put in `task` what would arrive as the request. Add `inputs` for values the skill expects from an earlier skill. For a skill that reads issues or pull requests, seed them under `forge`, and set `number` when the request is about one of them; then `task` can be left out. Design the case so that a wrong answer fails it: one clearly right category, one real bug, an upgrade that breaks the tests if it is applied. 4. **Check that the skill's goals can be met.** The skill's `goals.yaml` applies unchanged. A `build-feature` case needs a place for a test, because that skill requires a changed test path; a `fix-bug` case needs a test suite the subagent can name as `TEST_CMD`. 5. **Add `reference.patch`** if you want a similarity score: the human fix as a unified diff of the files in `repo/`. 6. **Check the layout.** This test loads every fixture and fails on a missing `case.yaml`, an empty `task`, a missing `repo/` or a `forge` section that does not build: ```sh go test ./internal/eval/ -run TestFixturesAreWellFormed ``` 7. **Add recordings.** The replay test runs every fixture, so a new case needs a `subagent:` recording, and a `judge:` recording when the skill has a judge, in `testdata/recordings/evals/.yaml`. Give each a `match` string that occurs in this case's task or `AGENTS.md` and in no other case of the skill. The tool calls must produce a result that passes the skill's checks, because the checks really run. 8. **Run the replay**, first as the Go test, then in real sandboxes. `make eval` rebuilds the binary, which is needed because fixtures are compiled in: ```sh go test ./internal/eval/ -run TestBuiltinSkillEvals make eval SKILL=fix-bug ``` 9. **Run it against a real model**, with `ANTHROPIC_API_KEY` set, to see how the skill does on the case without a script. This costs what the calls cost, and the record config sets no minimum pass rate, so read the output: ```sh KOJO_LIVE_MODELS=1 make eval SKILL=fix-bug EVAL_CONFIG=evals/kojo.record.yaml ``` ## The activation gate The dashboard's Skills studio takes a skill change through four steps: draft, test, eval, activate. Evals are the third step and can be made a condition of the fourth. - **Draft.** Someone with the `skill:edit` role edits a copy of the skill. A draft never runs in a real session. - **Test.** The draft runs against a chosen issue or pull request of an enabled repository, as a dry run. Each test run is attached to the draft. - **Eval.** The draft's files run over the fixtures of the skill with the same name. The run is attached to the draft. Saving new content to the draft clears its eval and its test runs. - **Activate.** Someone with the `operator` role makes the draft live. Activation is checked on the server against the activation policy, the `settings/activation` config object of the org: | Field | Type | Seeded from `kojo.yaml` | Effect | |---|---|---|---| | `require_eval` | boolean | `seed.activation.require_eval`, default false | The draft must be proven on its current content: by a finished eval, or by an accepted test run when the skill has no fixtures. | | `min_eval_pass_rate` | number, 0 to 1 | `seed.activation.min_eval_pass_rate`, default 0 | That eval's pass rate must be at least this. Also the default `--min-pass-rate` of `kojo eval`. | | `require_second_reviewer` | boolean | no seed key; starts false | The person who activates must have written none of the draft: not its author, nor anyone who edited it. | A draft is refused, with the reason, when its files do not validate, when its kit asks for more than the scope's egress limits, or when `require_second_reviewer` is set and someone who wrote it, its author or an editor, tries to activate it. Only an admin changes the policy. What the server checks when someone activates a draft, and what activation then does: ```mermaid flowchart TD A["Activate a draft"] --> V{"Files validate, kit inside the egress limits?"} V -- no --> X["Refused, with the reason"] V -- yes --> S{"require_second_reviewer set, and the author or an editor activates?"} S -- yes --> X S -- no --> E{"require_eval set?"} E -- no --> W{"Where the scope's skills are edited"} E -- yes --> F{"Skill has eval fixtures?"} F -- yes --> P{"Eval of the draft finished, pass rate at least the minimum?"} F -- no --> T{"A test run of the draft succeeded, accepted by the goal critic?"} P -- no --> X T -- no --> X P -- yes --> W T -- yes --> W W -- dashboard --> L["The draft becomes the live revision"] W -- git --> PR["A pull request with the skill's files"] ``` With `require_eval` set, what the draft needs depends on whether the skill has eval fixtures: | The skill | The draft needs | |---|---| | Has fixtures | An eval of the draft that has finished, with a pass rate of at least `min_eval_pass_rate`. | | Has no fixtures | At least one test run of the draft that ended as succeeded with the goal critic accepting the result. | Fixtures are compiled into the binary and matched by skill name. In this version every built-in skill has them; a skill you create under a new name has none and takes the test-run route. Because saving a draft clears its eval and its test runs, the proof is always of the content being activated. What activation does depends on where the scope's skills are edited. With the dashboard as the source, the draft becomes the live revision at once, for sessions that start from then on. With git as the source, activation opens a pull request with the files under `.factory/skills//`, and its description carries the eval's pass rate; the skill changes when that pull request is merged. The gate covers activation from the Skills studio. A skill edited by hand in a repository's `.factory/` takes effect when the commit reaches the default branch, without an eval. Review those changes like code, and run `kojo skills validate` on them in CI. Revisions, rollback and roles are in [Managing kōjō](/docs/manage/); the rest of the studio is on the [dashboard](/docs/manage/dashboard/#skills-studio) page. ### Proposals kōjō makes With [self-improvement](/docs/self-improvement/) on, kōjō writes drafts of its own: proposed changes to a skill's instructions or goals. Each is evaluated automatically, next to an eval of the version in use on the same fixtures, and closed as "did not hold up" when its pass rate is lower than the version in use's or below `min_eval_pass_rate`. A skill without fixtures is not measured, and its proposal says so. Approving a proposal is activating its draft through this gate, and only a person signed in to the dashboard can do it. --- > Source: https://xavidop.github.io/kojo/docs/memory # Memory kōjō remembers three kinds of things between sessions. All three are rows of one table in Postgres, and all three are searched the same way: by meaning when an [embedding model](/docs/models/) is configured and pgvector is available, by words otherwise. | Kind | Belongs to | Comes from | Read by | |---|---|---|---| | [Team memory](#team-memory) | A repository, or the whole org | Skills (`memory_save`), and operators in the dashboard, the API or MCP | Every session on that repository | | [Per-person memory](#per-person-memory) | One person | That person: in chat, in a mention, or in the dashboard | Only sessions that person starts | | [Lessons learned from reviews](#lessons-learned-from-reviews) | A repository, as team memory | A maintainer's review of a pull request kōjō opened | The skill that produced that pull request, the next time it runs there |
A tall filing cabinet beside a conveyor; a mechanical arm slips a card into an open orange drawer. A tall filing cabinet beside a conveyor; a mechanical arm slips a card into an open orange drawer.
What one session learns is filed away, and found again by the sessions that need it.
A memory is text a person wrote, or text distilled from it. It reaches a model as data: inside the same fence as an issue body, or as the result of a `memory_search` call, never as part of the instructions. See [Security](/docs/security/). The files under a repository's `.factory/memory/` are something else: notes kept in git and handed to every subagent as they are. They are described under [AGENTS.md and .factory/memory](/docs/skills/skill-md/#agentsmd-and-factorymemory) and are not copied into the database. ## Team memory Team memory holds facts about how a repository or the org works: "integration tests need Docker and are tagged `integration`", "releases are cut from `main` on Tuesdays". A memory with a repository applies to that repository; one without applies to every repository. It is written in three ways: - A skill that lists the `memory_save` tool saves a fact while it works. This only works in a session whose requester is trusted. A request from an untrusted actor cannot save team memory, because what was learned from untrusted input must not steer later sessions. - An operator adds a memory by hand, on the dashboard's Memory screen, with `POST /api/v1/memory` or with the MCP tool `kojo_memory_add`. - kōjō learns a [lesson from a review](#lessons-learned-from-reviews). It is read in two ways. Every subagent starts with up to five team memories that match its task, and the orchestrator and any skill that lists `memory_search` can search for more. Each memory records where it came from: | Source | Meaning | |---|---| | `session:` | A skill saved it in that session | | `user:` | Someone added it by hand | | `review::` | A lesson learned from that reviewer's feedback on pull request `` |
The Memory screen of the dashboard on its Team tab: a search box with a repository filter, and three team memories with their topic, the repository they apply to, where each came from and when it was saved.
Team memory in the dashboard: the Came from column turns the source into a link to the session or the review, or the name of the person who added it.
## Per-person memory A person can have memories of their own: preferences and context that apply to their requests and to nobody else's. "I review in the morning, keep pull requests under 200 lines." "Explain Rust lifetimes when you touch them." ### Saving one - Tell kōjō in chat or in a mention: "remember that I want pull requests under 200 lines". The orchestrator saves it with its `memory_save` tool, which only ever writes to the memory of the person who asked. - A skill that lists `memory_save` can save with `scope: personal`. The default scope is `team`; the tool's answer says which memory was written. - On the dashboard's Memory screen, choose "Mine" and add it, or choose "Only me" in the dialog. - `POST /api/v1/memory` with `"scope": "personal"`, or the MCP tool `kojo_memory_add` with `scope: personal`. A person does not need the operator role, or any trigger permission, to keep a memory of their own: it only ever reaches sessions they start themselves. One person can have at most 200. A personal memory saved by a session follows the person to every repository. One added through the API with a `repo` applies to their requests on that repository only. ### Which sessions read it Only a request a person made has a person: a mention on a forge, a chat message, a run started by hand from the dashboard, the CLI or MCP, or a [campaign](/docs/campaigns/) (its sessions are the person's who created it). Such a session gets that person's memories when it starts (up to 20, newest first, for the orchestrator and for every subagent), and its `memory_search` searches them along with team memory. Each search result says whether it is `team` or `personal`. A session nobody asked for works for the team and reads no personal memory: an automatic trigger such as `issue_opened`, a schedule, a review to learn from. Dry runs (skill tests and evals) read and save none either, so their results do not depend on who started them. ### Who is a person A person is identified by a key: | Where the request comes from | The key | |---|---| | Chat, when the surface gives kōjō the sender's email | `email:
` | | The dashboard, signed in through OIDC | `email:
` | | A forge mention | `:`, for example `github:ana` | | Chat, when the surface gives no email | `:`, for example `slack:u02abcdef` | | The API, the CLI or MCP with an API token | `token:` | An email is the person: it is the same key in chat and in the dashboard, so a preference saved in Slack applies to a run started from the dashboard by the same address. It is also what [roles](/docs/manage/) are granted to. A forge does not tell kōjō a user's email, so a forge login is a person of its own until an admin links it. The `identities` of the [`settings/memory`](/docs/manage/objects/#settingsmemory) object say which accounts belong to which email: ```yaml version: 1 objects: - scope: org object: settings/memory content: identities: - email: ana@example.com logins: ["github:ana", "forgejo:ana", "token:ana-laptop"] ``` With this, Ana's mentions on GitHub and Forgejo and the runs she starts with her API token read and write the same memory as her chat messages. kōjō never decides by itself that two accounts are the same human. An account that is not linked keeps a memory of its own, and that memory does not move when the account is linked later. Keys are lower case, and logins in `identities` are matched without case. A key is the account's name: when a forge account is renamed, what it saved stays under the old name. The same links decide whose [limits](/docs/models/#people) a session counts against: a linked login's sessions count under the email, whether or not per-person memory is on. ### Privacy A person's memories are theirs. - On the Memory screen, "Mine" lists only your own. `GET /api/v1/memory?scope=mine` does the same; the default listing and every search without `scope` return team memory only. - You delete your own memories, one at a time or all at once (`DELETE /api/v1/memory?person=`), whatever your role. - Nobody else sees them in a listing or a search, and to another user's `DELETE` they do not exist (`404`). - An admin can list one person's memories (`GET /api/v1/memory?person=`) and delete them, one or all, to answer a request for a copy or for erasure. Each of those is in the audit log: `memory.read`, `memory.delete` with `by_admin`, `memory.erase`. The audit entries name the person and the memory, not its text. ```sh # Everything kōjō remembers about one person, then all of it deleted (admin) curl -H "Authorization: Bearer $KOJO_TOKEN" \ "$KOJO_SERVER/api/v1/memory?person=email:ana@example.com" curl -X DELETE -H "Authorization: Bearer $KOJO_TOKEN" \ "$KOJO_SERVER/api/v1/memory?person=email:ana@example.com" ``` Sessions are a separate record. The [replay](/docs/observability/#session-replay) of a session a person started shows its tool calls, the results of a `memory_search` among them, and what the model answered. Everyone with the `viewer` role can read it, so what a person saved can show there. To turn per-person memory off for the whole install, set `personal: false` in `settings/memory`. Sessions then read and save none. What is already stored stays until its owners or an admin delete it. ## Lessons learned from reviews When a maintainer reviews a pull request kōjō opened, what they say can improve the next run. "We never mock the database in this repository" is worth remembering; "typo here" is not. ```mermaid flowchart TD C["A comment or review on a pull request"] --> W["Forge webhook"] W --> M{"Mentions kōjō?"} M -- yes --> R["A request, handled as a mention"] M -- no --> O{"Pull request opened by a kōjō session?"} O -- no --> I["Ignored"] O -- yes --> P{"Author has trigger_permission?"} P -- no --> X["Refused and audited"] P -- yes --> S["Feedback session queued"] S --> D["One model call distils general lessons"] D -- "nothing general" --> N["Session ends, nothing saved"] D -- "a lesson" --> T["Saved as team memory of the repository, for the skill"] T --> U["The skill's next run there starts with it"] ``` ### What counts as feedback Three things must hold: 1. **It is on kōjō's own pull request.** kōjō records every pull request a session opens. A comment on anyone else's pull request is ignored. 2. **Its author has the repository's `trigger_permission`** (default `write`), the same permission a mention needs. Anyone else's comment is refused and audited as `request.reject`, and reaches no model. A lesson is read by later sessions, so a stranger must not be able to plant one. 3. **It does not mention kōjō.** A comment that mentions the bot is a request, as always, and is handled as one and not also as feedback: on kōjō's own open pull request, a [follow-up](/docs/surfaces/triggers/#follow-ups) that commits to it. A comment that does not mention kōjō never changes the pull request. What each forge delivers: | Forge | A comment on the conversation | A review's summary | A comment on a line of the diff | |---|---|---|---| | GitHub | `issue_comment` | `pull_request_review` | `pull_request_review_comment`, with the diff hunk | | GitLab | Note Hook | Note Hook (GitLab has no separate review text) | Note Hook, with the file and line; kōjō reads the diff from the API | | Forgejo, Gitea | `issue_comment` | `pull_request_approved`, `pull_request_rejected`, `pull_request_comment` | Not delivered by the forge's webhooks | | Bitbucket | `pullrequest:comment_created` | None: a Bitbucket review has no text | `pullrequest:comment_created`, with the file and line | The events to enable are listed for [GitHub](/docs/surfaces/github/#events), [GitLab](/docs/surfaces/gitlab/#events), [Forgejo](/docs/surfaces/forgejo/#events) and [Bitbucket](/docs/surfaces/bitbucket/#events). A review without text (a bare approval) teaches nothing and is ignored. Edited comments are not read again. ### What happens to it The comment becomes a session with the trigger `feedback`, queued like any other. It runs no skill and needs no sandbox. It makes one model call on the `strong` tier with: - the comment, - the pull request's title and description, - the part of the diff the comment is on, or the beginning of the pull request's diff for a comment on the whole, - the skill that produced the change, - the lessons the repository already has. The model answers with up to three lessons, or none. A lesson is a short, general rule about the repository or about how its maintainers want work done, understandable without the pull request. A correction that only applies to that change, praise, a question, and anything about a person are not lessons. The session ends with the outcome `lessons_learned` or `nothing_learned`. It posts nothing on the pull request, whether it learned something, learned nothing or failed. Its model call is priced and counted against the [budgets](/docs/models/) like any other. ### What is saved Each lesson is saved as team memory of the repository, with: - the skill it concerns: the last skill of the session that changed files, the one whose work the reviewer read, - the source `review::`, and a link to the comment, - a one or two word topic. A lesson the repository already has is not saved twice: the model is shown the known lessons, the same sentence is recognised whatever its punctuation and capitals, and with an embedding model a lesson that means the same as a stored one is dropped too. Every saved lesson is in the audit log as `memory.learn`. ### How it is used A skill that runs on the repository starts with the lessons learned for it there (up to 20, newest first), ahead of the team memories that match its task. Lessons are team memory, so `memory_search` finds them as well. ### Finding and deleting a bad lesson On the dashboard's Memory screen, "Learned from reviews" lists every lesson with its skill, its repository, and the review it came from, as a link to the comment. An operator deletes one there; sessions stop seeing it at once. The same through the API: ```sh # The lessons learned for fix-bug in one repository curl -H "Authorization: Bearer $KOJO_TOKEN" \ "$KOJO_SERVER/api/v1/memory?repo=github/acme/api&skill=fix-bug&source=review:" curl -X DELETE -H "Authorization: Bearer $KOJO_TOKEN" \ "$KOJO_SERVER/api/v1/memory/mem_01jexample" ``` ### Turning learning off Learning is on by default. An admin turns it off for the org, or for one repository, with `learn_from_reviews` in the [`settings/memory`](/docs/manage/objects/#settingsmemory) object, or on the dashboard under Settings, Memory. ```yaml version: 1 objects: # Off everywhere... - scope: org object: settings/memory content: learn_from_reviews: false # ...except in this repository. - scope: repo:github/acme/api object: settings/memory content: learn_from_reviews: true ``` With learning off, review comments are not queued and reach no model. Lessons already saved stay, and are still given to their skills, until someone deletes them. ## What became of each pull request The same pull request events tell kōjō what happened to its pull requests after their sessions ended: merged, or closed without merging, and whether a person pushed commits first. That gives two numbers per repository and skill: - the **merge rate**: merged, out of merged and closed; - the **human-edit rate**: out of the merged ones, those a person pushed commits to before the merge. They are on the dashboard's overview next to the critic pass rate, in `GET /api/v1/stats`, and in Prometheus as `kojo_pull_requests_closed_total`. See [Prometheus metrics](/docs/observability/metrics/#merge-rate-and-human-edit-rate). Lessons and the fate of pull requests are also the evidence of [self-improvement](/docs/self-improvement/): with it turned on, kōjō proposes a change to a skill's instructions or goals once enough of it has gathered, and a person approves or rejects the proposal. ## Who can see and delete what | | See | Add | Delete | |---|---|---|---| | Team memory, lessons included | Everyone with a role | `operator`; skills in a trusted session; kōjō, from a review | `operator` | | Your personal memory | You | You, and sessions you start | You | | Someone else's personal memory | `admin`, by naming the person; audited | Nobody | `admin`; audited | The endpoints are listed in the [HTTP API](/docs/manage/api/), the tools in [MCP](/docs/manage/mcp/), and the audit actions in [Audit log](/docs/observability/audit-log/#actions-recorded). --- > Source: https://xavidop.github.io/kojo/docs/self-improvement # Self-improvement kōjō's skills are files: `SKILL.md`, `goals.yaml` and `kit.yaml` ([Skills](/docs/skills/)). Over time kōjō sees how each skill does. The goal critic rejects some of its results and says why, maintainers leave review comments that become [lessons](/docs/memory/#lessons-learned-from-reviews), and pull requests are closed unmerged or changed by a person before they are merged. With self-improvement turned on, kōjō turns that evidence into a proposal: a changed version of a skill's instructions or goals, with a rationale that cites the evidence item by item. The proposal is a skill draft written by kōjō. It is measured by [evals](/docs/evals/) against the version in use, and it only becomes the skill in use when a person approves it in the dashboard. kōjō never changes its own skills by itself. It is off by default.
A drafting table with a machine blueprint and an orange rubber stamp, beside a test bench that holds two versions of a part under a measuring arch. A drafting table with a machine blueprint and an orange rubber stamp, beside a test bench that holds two versions of a part under a measuring arch.
kōjō redraws a skill and measures the new version next to the one in use. Only a person's approval puts it into service.
## The loop ```mermaid flowchart TD E["Evidence: rejected results, lessons, pull requests"] --> T{"Enough, past the cooldown, no open proposal?"} T -- no --> W["Wait for more"] T -- yes --> M["One model call writes the changed files"] M --> C{"Checked in code: widens the skill, does not validate, cites nothing?"} C -- yes --> R["Closed as refused"] C -- no --> D["A draft by kōjō, with what it loosens listed"] D --> V["Evals of the draft and of the version in use"] V --> H{"Pass rate at least the version in use's and the policy's minimum?"} H -- no --> N["Closed as did not hold up"] H -- yes --> P["Ready: listed in the dashboard, announced in chat"] P --> A["A person approves: the draft is activated"] P --> J["A person rejects, with a reason kept"] ``` Every 15 minutes one server of the install looks at every scope where self-improvement is on and every skill it covers. It queues a proposal for a skill when the skill has no open proposal, its cooldown has passed since the last proposal, and enough new evidence has gathered since then. A proposal can also be asked for by hand, which skips the cooldown and reads the whole window of evidence (see [Start one by hand](#start-one-by-hand)). A proposal is written by a session of kind `improve`. It runs no skill and needs no sandbox: it gathers the evidence, makes one model call, checks the answer, and waits for the evals. Its result links to the proposal. There is one open proposal per skill and scope at a time. ## What counts as evidence | Kind | What | Where it links | |---|---|---| | Goal critic | A real run of the skill whose result the critic rejected, or accepted only after rejecting earlier attempts. The unmet criteria and the end of the failed checks' output are shown. | The session | | Lesson | A lesson learned from a maintainer's review of a pull request the skill produced | The review comment | | Pull request | A pull request of the skill that was closed without merging, merged only after a person pushed commits to it, or is open with a person's commits | The pull request | - Dry runs (skill tests, evals) are not evidence: a fixture says nothing about how a skill does on real work. - For a dashboard-managed or built-in skill, only the runs of the version in use count. For a skill kept in git, every run of it counts, since its commit moves with every push. - The org's proposals read the evidence of every repository that uses the org's skill. A repository's proposals read that repository's evidence only. - Evidence is read from the last `window_days` days, and never from before the last approved proposal for the skill: what came before was about the version it replaced. - The periodic check counts only the evidence that is newer than the last proposal for the skill, so the same evidence does not propose twice. - Every item counts towards `min_evidence`. The model is shown at most 10 critic results, 20 lessons and 10 pull requests. ## What the model is asked One call on the `strong` tier, with the purpose `improve`. It is shown the skill's `SKILL.md` and `goals.yaml` as they are in use, how the skill did (runs, accepted runs, pull requests merged and closed), the evidence under references `E1`, `E2`, ..., and the earlier proposals for the skill that did not go through: rejected (with the maintainer's reason), did worse in the evals, or refused. All of that is data. Evidence comes from review comments and from the output of repository code, so it reaches the model inside the same fence as an issue body ([Security](/docs/security/)), and the instructions tell the model that text in it asking for a tool, a host, a credential or an approval is evidence of nothing but itself. The limits below do not rely on the model following that: they are checked in code. The model answers with the complete new `SKILL.md` and `goals.yaml` (or leaves one as it is), a summary, and the list of changes with the references of the evidence each answers. It can also answer that the evidence shows no pattern worth a change. With the mock provider the call is replayed from a recording whose purpose is `improve` ([Local stacks](/docs/development/local-stacks/#mock-models-produce-canned-output)). ## What a proposal may and may not change A proposal writes `SKILL.md` and `goals.yaml`. Every other file of the skill is copied from the version in use. Then kōjō parses the proposed skill and compares it with the one in use, field by field. These are refused, and the proposal is closed as `refused` with the list: - a new tool, a renamed skill, or a higher model tier (or a tier kōjō cannot rank); - any change to any file other than `SKILL.md` and `goals.yaml`, the kit first of all: image, resources, egress hosts, credentials, `needs_docker`, setup commands, or a `kit:` pointing at another file; - removing `no_changes`, or `confidential`; - a check on a skill that has no sandbox, or a new or rewritten check command on a skill without the `exec` tool (a check is a command); - a judge on a higher or unknown model tier. The proposed files must also pass the same validation as any draft (they parse, and the kit stays inside the scope's [`settings/egress`](/docs/manage/objects/#settingsegress)), and the proposal must cite at least one piece of the evidence it was given. A reference the model made up is dropped. A proposal whose files are those of a proposal a maintainer rejected is closed as `nothing_to_propose`, with the earlier reason. Changes that make the goals easier to meet are allowed, as a separate list on the proposal that the approver sees before anything else: - `max_attempts` raised, or `max_steps` raised; - a check removed, its command changed, `expect_failure` added or removed, `skip_if_unset` added, or its timeout raised; - `max_changed_lines` raised or removed, a forbidden path removed, `required_paths` removed or given another pattern; - the judge removed, a rubric item dropped or reworded, or the judge moved to a lower tier; - an output no longer required. kōjō finds these by comparing the two goals files, not by asking the model. A tool removed or a lower tier narrows the skill and is not listed. ## How it is measured When the proposal passes those checks it becomes a draft whose author is `kojo`, and two evals start: one of the draft, and one of the version in use, run as a copy of it so the comparison is with exactly the files the scope resolves. An eval of the version in use with the same files from the last seven days is reused instead of running again. The proposal waits for both, for six hours at most. | Result | Status | |---|---| | The proposal's pass rate is lower than the version in use's | `did_not_hold_up`, with both numbers | | It is below `min_eval_pass_rate` of [`settings/activation`](/docs/evals/#the-activation-gate) | `did_not_hold_up`, with the numbers | | Otherwise | `ready`, with both numbers | A skill without eval fixtures cannot be measured this way. Its proposal goes to `ready` unmeasured, and says plainly that there was nothing to measure it against. If the activation policy requires an eval, approving it then needs a test run of the draft that the goal critic accepted, as for any draft of such a skill. | Status | Meaning | |---|---| | `proposing` | Queued, or the model is writing it | | `evaluating` | Its draft exists and the evals run | | `ready` | It held up and waits for a person | | `approved` | A person activated it | | `rejected` | A person turned it down; the reason is kept | | `did_not_hold_up` | Its pass rate was below the version in use's or the policy's minimum | | `refused` | It tried to change what a proposal may not, or did not validate, or cited nothing | | `nothing_to_propose` | The evidence showed no pattern, the answer changed nothing, it repeated a rejected change, or by the time it was written the evidence was below the threshold or self-improvement was off | | `failed` | Its session failed before a result. A failed proposal does not start the cooldown. | ## Who approves Only a person. Approving a proposal activates its draft through the [activation gate](/docs/evals/#the-activation-gate), and on top of that gate: - The caller must be a person signed in to the dashboard with the `operator` role. An API token is refused with 403 whatever its role, so no script, CLI, MCP client or automation acting for someone can approve one, neither through the proposal nor by activating its draft. Sessions and schedules have no way to activate anything. - The proposal must be `ready`, and its files must still not widen the skill as it is in use at that moment. - kōjō wrote the proposal, so for `require_second_reviewer` the person who approves is the second reviewer, unless they edited the proposal themselves, last or at any time before. A person may edit a ready proposal in the Skills studio before approving it. The edit is held to the same limits: saving files that would widen the skill is refused. The proposal then records who edited it and what it loosens now, and the eval it was measured with no longer counts: run an eval of the draft again. A proposal's draft cannot be deleted; reject the proposal instead. Rejecting takes an optional reason, which the next proposal for the skill is shown, and the same files are not proposed again. When activation goes through, the proposal is `approved` with the approver's name, and what the new version is judged on starts from there. Where the scope's skills are kept in git, approving opens the pull request, as activating any draft does. ## Telling the maintainers A proposal that is ready is listed in the dashboard: in **Skills**, under "Proposed by kōjō", and on the skill's row. With `notify` set, a chat message also goes to that channel, with the summary, the numbers, how many goals it loosens and the link to the proposal. A channel that cannot be reached does not undo the proposal. ## Turn it on The [`settings/improvement`](/docs/manage/objects/#settingsimprovement) object turns it on for one scope. Only an admin changes it, in the dashboard under Settings, Self-improvement, with [`kojo config apply`](/docs/manage/cli/#config-as-code), or through the API. The org's object covers the org's skills. A repository's object covers the skills that repository resolves; a repository does not inherit the org's object. ```yaml version: 1 objects: - scope: org object: settings/improvement content: enabled: true # Empty means every skill of the scope. skills: [fix-bug, review-pr] # At least 2: one data point is not a pattern. min_evidence: 5 window_days: 30 cooldown_days: 7 # A channel ID, or surface:channel when there is more than one chat surface. notify: slack:C0123ABC - scope: repo:github/acme/api object: settings/improvement content: enabled: true ``` | Key | Default | Meaning | |---|---|---| | `enabled` | `false` | Propose changes to this scope's skills | | `skills` | All | Only these skills | | `min_evidence` | `3` | Evidence a proposal needs | | `window_days` | `30` | How far back evidence is read | | `cooldown_days` | `7` | Least time between two proposals the periodic check makes for one skill | | `notify` | None | The chat channel told when a proposal is ready | ## Start one by hand Someone with the `operator` role can ask for a proposal for one skill now. It is refused when self-improvement is off for the skill, when the evidence is below `min_evidence`, and while the skill has an open proposal. It does not wait for the cooldown. - Dashboard: **Propose a change** on the skill's row in Skills. - API: `POST /api/v1/proposals` with `{"scope": "org", "skill": "fix-bug"}` ([HTTP API](/docs/manage/api/#skill-proposals)). - MCP: `kojo_proposal_start` ([Manage with MCP](/docs/manage/mcp/#skill-proposals)). - CLI: [`kojo skills propose`](/docs/cli/#kojo-skills-propose). ```sh kojo skills propose fix-bug kojo skills proposals --open ``` ## What it costs - One model call on the `strong` tier per proposal. Its prompt carries the skill's `SKILL.md` (up to 24 KiB) and `goals.yaml` (up to 12 KiB), the evidence and the earlier proposals. The call is priced into the proposal's session like any other. - Two eval runs per proposal that passes the checks: the draft, and the version in use unless a run of the same files from the last seven days is reused. Each runs every fixture case of the skill as a dry-run session, with its model calls and sandboxes. That is usually most of the cost. - A proposal that is refused, has nothing to propose or repeats a rejected change costs the model call only. - While the daily budget of [`settings/models`](/docs/models/) is spent, a proposal waits like any session. `cooldown_days` and `min_evidence` bound how often this happens per skill; `skills` bounds which skills it happens for. ## Read a proposal A proposal's page in the dashboard (`/skills/proposals/`) has, from the top: 1. What it loosens, in a box that is never folded away, and, if the skill in use changed since and the proposal would now widen it, why approval will be refused. 2. The numbers: its pass rate, the version in use's, how many goals it loosens and how many pieces of evidence it rests on. 3. Why: the summary, and each change with the references of the evidence it answers. A reference links to the item below. 4. The evidence, each item with its kind, date and repository, and a link to the session, the pull request or the review. 5. The changes: a diff of each file against the version in use now. 6. The eval, case by case: whether each case passed for the version in use and for the proposal, and which ones changed. 7. The decision: approve and activate, reject with a reason, or open the draft in the studio to edit or test it first.
A proposal page for fix-bug, ready for review: a box saying it loosens the bar in one way (max_attempts raised from 3 to 4), its pass rate of 100% against 75% for the version in use, the rationale with the evidence each change answers, and the start of the evidence list.
The top of a ready proposal: items 1 to 4 of the list, with the evidence references (E1, E2, …) under each change.
The same is in `GET /api/v1/proposals/{id}` and the MCP tool `kojo_proposal`. Every step is in the [audit log](/docs/observability/audit-log/#actions-recorded) as `skill.proposal.start`, `create`, `validate`, `close`, `approve` and `reject`, and counted by `kojo_skill_proposals_total` and `kojo_skill_proposal_outcomes_total` ([Prometheus metrics](/docs/observability/metrics/#factory-metrics)). --- > Source: https://xavidop.github.io/kojo/docs/config-reference `kojo.yaml` is the deployment config: what the process needs to start. Everything the team tunes afterwards (skills, repositories, schedules, model tiers, budgets, merge policy, access) is runtime config, changed live in the dashboard. Values may reference environment variables: `${NAME}`, or `${NAME:-default}`. A referenced variable that is unset and has no default is an error. Unknown keys are errors. The JSON Schema is published at [`https://xavidop.github.io/kojo/schema/kojo.schema.json`](https://xavidop.github.io/kojo/schema/kojo.schema.json) and printed by `kojo schema kojo`. ## Examples A complete file for each supported deployment. Each section below has shorter examples of its own. `kojo config validate -f kojo.yaml` checks a file without starting anything. ### Single VM with Docker Sandboxes A single VM: kōjō runs on the host next to Docker Sandboxes (`sbx`), and Postgres runs in Docker Compose. The `${NAME}` values come from the environment, usually an `.env` file that the systemd unit loads. ```yaml server: # How forges, Slack and browsers reach kōjō. public_url: "${KOJO_PUBLIC_URL}" # Loopback: a TLS reverse proxy in front of kōjō takes the public traffic, # the forges' webhooks included. listen: "127.0.0.1:8080" auth: # Signs the dashboard's session cookie. session_secret: "${KOJO_SESSION_SECRET}" # Sign-in for people. oidc: issuer: https://accounts.google.com client_id: "${OIDC_CLIENT_ID}" client_secret: "${OIDC_CLIENT_SECRET}" allowed_domains: [example.com] # Written to the rbac object with the admin role on the first start. admins: [ana@example.com] # A static API token for the CLI, CI and MCP clients. tokens: - name: admin token: "${KOJO_ADMIN_TOKEN}" role: admin database: # The Postgres of docker-compose.yml, published on loopback. url: "postgres://kojo:${POSTGRES_PASSWORD}@127.0.0.1:5432/kojo?sslmode=disable" forges: # The GitHub App that `kojo setup github` creates. github: app_id: "${GITHUB_APP_ID}" private_key_file: /etc/kojo/secrets/github-app.pem webhook_secret: "${GITHUB_WEBHOOK_SECRET}" chat: slack: # Socket mode needs no inbound connection. mode: socket bot_token: "${SLACK_BOT_TOKEN}" app_token: "${SLACK_APP_TOKEN}" models: # kōjō calls the providers itself. gateway: embedded providers: anthropic: api_key: "${ANTHROPIC_API_KEY}" # Tiers and budgets are initial values: after the first start they are the # settings/models object. tiers: fast: provider: anthropic model: claude-haiku-5-5 # USD per million tokens. Without a price the tier's calls cost 0 and # the budgets do not bound them. price: input_per_mtok: 0.10 output_per_mtok: 0.50 strong: provider: anthropic model: claude-opus-5-5 price: input_per_mtok: 4 output_per_mtok: 20 budgets: per_session_usd: 10 per_day_usd: 200 sandbox: # One microVM per session. sbx enforces egress and injects credentials with # its own proxy on the host, so this driver takes no sandbox.proxy block. driver: sbx defaults: # Draft pull requests only. merge_policy: draft_only ``` ### Kubernetes with Agent Sandbox Kubernetes with the `k8s` driver (Agent Sandbox). The Helm chart renders this file from its `config` value and sets `server.listen`, `database.url`, `sandbox.driver`, `sandbox.k8s.namespace`, `sandbox.k8s.runtime_class` and `sandbox.proxy` itself; with `existingConfigMap` you write the whole file. The chart sets the `DATABASE_URL`, `KOJO_SESSION_SECRET`, `KOJO_SANDBOX_NAMESPACE` and `KOJO_PROXY_*` variables; the others come from your Secret. ```yaml server: public_url: https://kojo.example.com listen: ":8080" # Sessions each replica runs at once. workers: 4 auth: # Shared by every replica, so a sign-in works on all of them. session_secret: "${KOJO_SESSION_SECRET}" oidc: issuer: https://accounts.google.com client_id: "${OIDC_CLIENT_ID}" client_secret: "${OIDC_CLIENT_SECRET}" allowed_domains: [example.com] admins: [ana@example.com] tokens: - name: ci token: "${KOJO_CI_TOKEN}" role: operator database: url: "${DATABASE_URL}" forges: github: app_id: "${GITHUB_APP_ID}" # Mounted from a Secret with the chart's extraVolumes. private_key_file: /secrets/github-app.pem webhook_secret: "${GITHUB_WEBHOOK_SECRET}" chat: slack: mode: socket bot_token: "${SLACK_BOT_TOKEN}" app_token: "${SLACK_APP_TOKEN}" models: gateway: embedded providers: anthropic: api_key: "${ANTHROPIC_API_KEY}" tiers: fast: provider: anthropic model: claude-haiku-5-5 price: input_per_mtok: 0.10 output_per_mtok: 0.50 strong: provider: anthropic model: claude-opus-5-5 price: input_per_mtok: 4 output_per_mtok: 20 budgets: per_session_usd: 10 per_day_usd: 200 sandbox: driver: k8s k8s: namespace: "${KOJO_SANDBOX_NAMESPACE}" # The RuntimeClass of every sandbox pod: kata, gvisor or a name of your # cluster. runtime_class: kata # Pods kept ready per sandbox template. warm_pool_size: 2 # kojo-proxy is its own deployment: sandboxes reach the network only # through it. Its replicas are found through the admin URL's name (the # chart's headless proxy-admin Service), and each gets every policy. proxy: mode: remote listen: ":3128" admin_listen: ":3129" advertise_url: "${KOJO_PROXY_ADVERTISE_URL}" admin_url: "${KOJO_PROXY_ADMIN_URL}" admin_discovery: dns admin_token: "${KOJO_PROXY_ADMIN_TOKEN}" ca_cert_file: /var/run/kojo/proxy-ca/tls.crt ca_key_file: /var/run/kojo/proxy-ca/tls.key ttl: 4h defaults: merge_policy: draft_only seed: activation: # Activating a skill draft needs an eval with a pass rate of at least 0.7. require_eval: true min_eval_pass_rate: 0.7 telemetry: otlp_endpoint: http://otel-collector.observability.svc:4318 ``` ## Top level | Key | Type | Description | |---|---|---| | `dev` | boolean | Dev turns on development mode: it allows the insecure sandbox drivers (docker, fake), runc on Kubernetes and a dashboard without OIDC. kojo doctor fails a production check while it is set. | | `server` | object | | | `database` | object | | | `forges` | object | | | `chat` | object | | | `trackers` | object | Trackers are the issue trackers kōjō takes work from: Linear, Jira Cloud and Asana. | | `alerts` | object | Alerts are the sources of production alerts kōjō takes work from: Sentry and Datadog Error Tracking. | | `models` | object | | | `sandbox` | object | | | `defaults` | object | Defaults are initial values only: after install they are managed in the dashboard and stored as config revisions. | | `seed` | object | Seed is only read on the first start against an empty database. | | `telemetry` | object | | ### `server` | Key | Type | Description | |---|---|---| | `public_url` | string | PublicURL is how forges, Slack and browsers reach kōjō. | | `listen` | string | Listen is the address to bind. Default ":8080". | | `metrics_listen` | string | MetricsListen is the address /metrics is served on, apart from the dashboard, the API and the webhooks, so that putting Listen on a public network does not publish the metrics. "off" serves none. Default "127.0.0.1:9090"; the Helm chart sets ":9090". | | `auth` | object | | | `workers` | integer | Workers is how many sessions this replica runs at once. Default 4. | | `network_policy` | boolean | NetworkPolicy says whether NetworkPolicies limit who reaches Postgres, kojo-proxy's admin port and the metrics port. The Helm chart sets it from networkPolicy.enabled, and `kojo doctor` warns when it is false. Unset, kōjō does not know and doctor does not check. | OIDC sign-in for people, one admin seeded on the first start, and a static API token for CI. ```yaml server: public_url: https://kojo.example.com listen: ":8080" workers: 8 auth: session_secret: "${KOJO_SESSION_SECRET}" oidc: issuer: https://accounts.google.com client_id: "${OIDC_CLIENT_ID}" client_secret: "${OIDC_CLIENT_SECRET}" scopes: [openid, email, profile] allowed_domains: [example.com] admins: [ana@example.com] tokens: - name: ci token: "${KOJO_CI_TOKEN}" role: operator ``` #### `server.auth` | Key | Type | Description | |---|---|---| | `oidc` | object | | | `tokens` | list of objects | Tokens are static API tokens for the CLI, CI and MCP clients. | | `admins` | list of strings | Admins are the emails written to the rbac object with the admin role on the first start against an empty database. After that, roles are managed in the dashboard and a change here has no effect. | | `session_secret` | string | SessionSecret signs the dashboard's session cookie. When empty a random one is generated at start, which signs everyone out on restart and does not work with more than one replica. | #### `server.auth.oidc` | Key | Type | Description | |---|---|---| | `issuer` | string | | | `client_id` | string | | | `client_secret` | string | | | `scopes` | list of strings | | | `allowed_domains` | list of strings | AllowedDomains restricts sign-in to these email domains. | | `trust_unverified_email` | boolean | TrustUnverifiedEmail accepts an ID token that has no email_verified claim, for identity providers that never send it (Microsoft Entra ID and AD FS among them). Without it, such a token is refused: a provider that does not vouch for an address may let a person pick anyone's, an admin's included. Turn it on only for a provider whose addresses your organization assigns. A token whose email_verified is false is refused either way. | #### `server.auth.tokens` | Key | Type | Description | |---|---|---| | `name` | string | | | `token` | string | | | `role` | string | Role is viewer, skill:edit, operator or admin. Default operator. | ### `database` | Key | Type | Description | |---|---|---| | `url` | string | | | `max_conns` | integer | MaxConns is the size of the connection pool: 0 for pgx's default (the larger of 4 and the number of CPUs), otherwise at least 2, because a campaign update holds one connection while it uses another. | The password comes from a variable, and the pool is capped at 20 connections. ```yaml database: url: "postgres://kojo:${POSTGRES_PASSWORD}@db.example.com:5432/kojo?sslmode=require" max_conns: 20 ``` ### `forges` | Key | Type | Description | |---|---|---| | `github` | object | | | `gitlab` | object | | | `forgejo` | object | | | `bitbucket` | object | | One block per forge. Configure only the ones you use. ```yaml forges: github: app_id: "${GITHUB_APP_ID}" private_key_file: /etc/kojo/secrets/github-app.pem webhook_secret: "${GITHUB_WEBHOOK_SECRET}" gitlab: base_url: https://gitlab.example.com token: "${GITLAB_TOKEN}" webhook_secret: "${GITLAB_WEBHOOK_SECRET}" forgejo: base_url: https://git.example.com token: "${FORGEJO_TOKEN}" webhook_secret: "${FORGEJO_WEBHOOK_SECRET}" bitbucket: workspace: acme token: "${BITBUCKET_TOKEN}" webhook_secret: "${BITBUCKET_WEBHOOK_SECRET}" ``` GitHub Enterprise Server, with the App's private key passed in a variable instead of a file. ```yaml forges: github: app_id: "${GITHUB_APP_ID}" private_key: "${GITHUB_APP_PRIVATE_KEY}" webhook_secret: "${GITHUB_WEBHOOK_SECRET}" base_url: https://ghe.example.com/api/v3 ``` #### `forges.github` | Key | Type | Description | |---|---|---| | `app_id` | string | | | `private_key_file` | string | PrivateKeyFile is the App's PEM private key. PrivateKey holds the PEM itself instead (from an environment variable). | | `private_key` | string | | | `webhook_secret` | string | | | `base_url` | string | BaseURL is the API root of a GitHub Enterprise Server (https://ghe.example.com/api/v3). Empty means github.com. | #### `forges.gitlab` | Key | Type | Description | |---|---|---| | `base_url` | string | BaseURL defaults to https://gitlab.com. | | `token` | string | | | `webhook_secret` | string | WebhookSecret is the webhook's secret token (X-Gitlab-Token). | #### `forges.forgejo` | Key | Type | Description | |---|---|---| | `base_url` | string | | | `token` | string | | | `webhook_secret` | string | | #### `forges.bitbucket` | Key | Type | Description | |---|---|---| | `workspace` | string | Workspace is the workspace ID (slug) whose repositories kōjō lists. | | `token` | string | Token is an API token with scopes of the bot's Atlassian account. | | `webhook_secret` | string | WebhookSecret is the secret of the repositories' webhooks (X-Hub-Signature). | ### `chat` | Key | Type | Description | |---|---|---| | `slack` | object | | | `teams` | object | | | `discord` | object | | | `mattermost` | object | | Slack in socket mode: kōjō opens the connection, so Slack needs no route to it. ```yaml chat: slack: mode: socket bot_token: "${SLACK_BOT_TOKEN}" app_token: "${SLACK_APP_TOKEN}" ``` Discord: kōjō opens the gateway connection, so Discord needs no route to it. Roles of one server decide who may do what. ```yaml chat: discord: bot_token: "${DISCORD_BOT_TOKEN}" application_id: "1200000000000000001" guild_id: "1100000000000000001" # the server kōjō serves roles: # Discord role ID: kōjō role "1100000000000000002": operator # @maintainers may start work and approve "1100000000000000003": skill:edit users: # Discord user ID: email of an rbac entry "1300000000000000001": ana@example.com ``` Slack in http mode: Slack sends events to kōjō's public URL, and the signing secret verifies them. ```yaml chat: slack: mode: http bot_token: "${SLACK_BOT_TOKEN}" signing_secret: "${SLACK_SIGNING_SECRET}" ``` Mattermost: kōjō signs in as a bot account and opens a WebSocket to the server. The server calls kōjō's public URL when someone clicks an approval button, and the action secret tells those calls from forged ones. ```yaml chat: mattermost: url: https://chat.example.com token: "${MATTERMOST_BOT_TOKEN}" action_secret: "${MATTERMOST_ACTION_SECRET}" ``` Microsoft Teams: a single-tenant Azure Bot whose messaging endpoint is the public URL followed by /teams/messages. Teams calls kōjō there, so the public URL must be https. ```yaml chat: teams: app_id: 6f9619ff-8b86-4d11-b42d-00c04fc964ff # the bot's Microsoft App ID app_password: "${TEAMS_APP_PASSWORD}" # a client secret of that app tenant_id: 72f988bf-86f1-41af-91ab-2d7cd011db47 # the bot's App Tenant ID ``` #### `chat.slack` | Key | Type | Description | |---|---|---| | `mode` | string | Mode is socket (no public ingress needed) or http. Default socket. | | `bot_token` | string | | | `app_token` | string | AppToken is the app-level token (xapp-...) Socket Mode needs. | | `signing_secret` | string | SigningSecret verifies requests in http mode. | | `api_url` | string | APIURL overrides https://slack.com/api/ (the Slack mock in dev stacks). | #### `chat.teams` | Key | Type | Description | |---|---|---| | `app_id` | string | AppID is the bot's Microsoft App ID (the application's client ID). | | `app_password` | string | AppPassword is the application's client secret. | | `tenant_id` | string | TenantID is the Microsoft Entra tenant of a single-tenant bot registration (its App Tenant ID): the bot gets its token from this tenant and serves only this tenant's users. Empty means a multi-tenant registration, which needs allowed_tenants. | | `allowed_tenants` | list of strings | AllowedTenants are further tenants whose users may talk to the bot. A multi-tenant registration has no tenant_id and must list its tenants here: anyone can install a multi-tenant bot, and kōjō trusts the email a tenant reports for a user. | | `text_format` | string | TextFormat is how messages are sent: extendedmarkdown (default; headings, lists, code blocks and tables) or markdown, Teams' older format, in which kōjō sends tables as code blocks. | | `service_url` | string | ServiceURL is the Bot Connector endpoint for messages that answer no incoming one, such as a schedule's notify. Default https://smba.trafficmanager.net/teams/ (the public cloud). kōjō sends the bot's token only to the Teams endpoints it knows and to this host. | | `login_url` | string | LoginURL overrides https://login.microsoftonline.com, where the bot gets its access token (sovereign clouds, a mock in tests). | | `token_scope` | string | TokenScope overrides https://api.botframework.com/.default. | | `openid_metadata_url` | string | OpenIDMetadataURL overrides https://login.botframework.com/v1/.well-known/openidconfiguration, the document that names the keys incoming requests are signed with. | #### `chat.discord` | Key | Type | Description | |---|---|---| | `bot_token` | string | BotToken is the bot's token from the Discord developer portal. | | `application_id` | string | ApplicationID is the application the bot belongs to. When set, kojo doctor checks that the token is that application's. | | `guild_id` | string | GuildID is the ID of the server kōjō serves. Messages from other servers are ignored, and a direct message is only taken from a member of this server. | | `roles` | map | Roles maps the ID of a role of that server to a kōjō role: viewer, skill:edit, operator or admin. Discord gives a bot no email, so this is how a sender gets a role; someone without a mapped role is answered read-only. The server's own ID stands for @everyone. | | `users` | map | Users maps a Discord user ID to the email of that person's entry in the rbac object, for people whose roles are managed there. Those roles add to the ones from Roles. | | `api_url` | string | APIURL overrides https://discord.com/api (a mock in tests). | #### `chat.mattermost` | Key | Type | Description | |---|---|---| | `url` | string | URL is the server's base URL (https://chat.example.com). | | `token` | string | Token is the bot account's access token. | | `action_secret` | string | ActionSecret signs the buttons kōjō posts, so a click can be told from a forged request. Generated at start when empty, which does not survive a restart or work with several replicas. | ### `trackers` | Key | Type | Description | |---|---|---| | `linear` | object | | | `jira` | object | | | `asana` | object | | Issue trackers: a ticket assigned to kōjō's account, a comment that mentions it, or one of the labels added starts a session on the repository the repos object maps the ticket to (`tickets`). Each tracker sends webhooks to `/webhooks/`; `kojo setup linear|jira|asana` prints what to configure. ```yaml trackers: linear: api_key: "${LINEAR_API_KEY}" # personal API key of kōjō's Linear user webhook_secret: "${LINEAR_WEBHOOK_SECRET}" labels: [kojo] # adding this label also starts work status: # off unless set started: In Progress review: In Review jira: base_url: https://acme.atlassian.net email: kojo@acme.example # the account of the API token api_token: "${JIRA_API_TOKEN}" webhook_secret: "${JIRA_WEBHOOK_SECRET}" users: # Atlassian account ID: email of an rbac entry "557058:f58131cb-b67d-43c7-b30d-6b58d40bd077": ana@example.com asana: token: "${ASANA_TOKEN}" webhook_secrets: ["${ASANA_WEBHOOK_SECRET_1}"] # written by kojo setup asana users: # Asana user ID: email of an rbac entry "1200000000000001": ana@example.com ``` #### `trackers.linear` | Key | Type | Description | |---|---|---| | `api_key` | string | APIKey is a personal API key of kōjō's Linear user (Settings, Security & access). Tickets are assigned to and mentions name that user. | | `webhook_secret` | string | WebhookSecret is the signing secret Linear shows on the webhook's page. Deliveries whose Linear-Signature does not verify are refused. | | `labels` | list of strings | Labels start work when added to an issue, or when an issue is created with one. | | `status` | object | Status moves an issue through its team's workflow states, by name. | | `users` | map | Users maps a Linear user ID to the email of that person's entry in the rbac object, for a person whose Linear address is not that one. Everyone else is known by the email Linear reports. | | `api_url` | string | APIURL overrides https://api.linear.app/graphql (a mock in tests). | #### `trackers.linear.status` | Key | Type | Description | |---|---|---| | `started` | string | Started is the status a ticket moves to when a session that may change code is queued for it ("In Progress"). | | `review` | string | Review is the status a ticket moves to when its session opens a pull request ("In Review"). | #### `trackers.jira` | Key | Type | Description | |---|---|---| | `base_url` | string | BaseURL is the site's address, such as https://acme.atlassian.net. | | `email` | string | Email is the address of kōjō's Atlassian account, which signs in with APIToken. | | `api_token` | string | APIToken is an API token of that account (without scopes: a scoped token only works through api.atlassian.com). | | `webhook_secret` | string | WebhookSecret is the secret of the webhook (Jira settings, System, WebHooks). Jira signs each delivery with it (X-Hub-Signature); deliveries that are not signed with it are refused. | | `labels` | list of strings | Labels start work when added to an issue, or when an issue is created with one. | | `status` | object | Status moves an issue through its workflow: the transition to the status of that name is made. | | `users` | map | Users maps an Atlassian account ID to the email of that person's entry in the rbac object. Jira gives a bot no email it can rely on, so this is how a person gets a role; anyone else's requests are read-only. | #### `trackers.jira.status` | Key | Type | Description | |---|---|---| | `started` | string | Started is the status a ticket moves to when a session that may change code is queued for it ("In Progress"). | | `review` | string | Review is the status a ticket moves to when its session opens a pull request ("In Review"). | #### `trackers.asana` | Key | Type | Description | |---|---|---| | `token` | string | Token is a personal access token of kōjō's Asana user, or a service account's token. | | `webhook_secrets` | list of strings | WebhookSecrets are the secrets of kōjō's webhooks, one per project (Asana gives each webhook its own, once, when it is created; kojo setup asana writes them to a file). A delivery signed with none of them is refused. | | `status` | object | Status moves a task to the section of that name in its project. | | `users` | map | Users maps an Asana user ID (gid) to the email of that person's entry in the rbac object. Asana does not say whether the address it reports was verified, so this is how a person gets a role; anyone else's requests are read-only. | | `api_url` | string | APIURL overrides https://app.asana.com/api/1.0 (a mock in tests). | #### `trackers.asana.status` | Key | Type | Description | |---|---|---| | `started` | string | Started is the status a ticket moves to when a session that may change code is queued for it ("In Progress"). | | `review` | string | Review is the status a ticket moves to when its session opens a pull request ("In Review"). | ### `alerts` | Key | Type | Description | |---|---|---| | `sentry` | object | | | `datadog` | object | | Production alerts: a Sentry alert rule whose action is kōjō's internal integration starts a session on the repository the repos object maps the error's project to (`alerts`). Sentry sends the webhooks to `/webhooks/sentry`; `kojo setup sentry` prints what to configure. ```yaml alerts: sentry: base_url: https://sentry.io # the default; a region's or a self-hosted install's org: acme # the organization's slug client_secret: "${SENTRY_CLIENT_SECRET}" # the internal integration's Client Secret token: "${SENTRY_TOKEN}" # a token of the integration, Issue & Event: Read ``` Datadog Error Tracking: a monitor grouped by `issue.id` and `service` notifies a webhook that sends `/webhooks/datadog` the monitor's IDs and scope, with the secret in a header; kōjō reads the issue and its stack trace with the keys. `kojo setup datadog` prints what to configure. ```yaml alerts: datadog: site: datadoghq.com # the default; us3.datadoghq.com, datadoghq.eu, ... api_key: "${DD_API_KEY}" app_key: "${DD_APP_KEY}" # an application key with error_tracking_read webhook_secret: "${KOJO_DATADOG_WEBHOOK_SECRET}" # at least 32 bytes: openssl rand -hex 32 ``` #### `alerts.sentry` | Key | Type | Description | |---|---|---| | `base_url` | string | BaseURL is Sentry's address: https://sentry.io (the default), a region's (https://de.sentry.io), or a self-hosted install's. | | `org` | string | Org is the organization's slug, as in its URLs. Alerts of another organization are ignored. | | `client_secret` | string | ClientSecret is the internal integration's Client Secret: Sentry signs every webhook with it. Deliveries whose Sentry-Hook-Signature does not verify are refused. | | `token` | string | Token is a token of the internal integration, with Issue & Event: Read. kōjō reads an alert's issue with it (its status and counts). | #### `alerts.datadog` | Key | Type | Description | |---|---|---| | `site` | string | Site is the organization's Datadog site: datadoghq.com (the default), us3.datadoghq.com, us5.datadoghq.com, datadoghq.eu, ap1.datadoghq.com, ap2.datadoghq.com, uk1.datadoghq.com, ddog-gov.com or us2.ddog-gov.com. The API is at api.. | | `api_key` | string | APIKey is an API key of the organization, sent as DD-API-KEY. | | `app_key` | string | AppKey is an application key with the error_tracking_read permission, sent as DD-APPLICATION-KEY. kōjō reads issues with it and writes nothing. | | `webhook_secret` | string | WebhookSecret is what the webhook sends in its X-Kojo-Webhook-Secret header, at least 32 bytes. Datadog does not sign webhooks: a delivery without this value is refused. | | `base_url` | string | BaseURL replaces https://api., for a proxy or a test. | ### `models` | Key | Type | Description | |---|---|---| | `gateway` | string | Gateway is "embedded" (Genkit runs in the kōjō process and calls the providers directly) or the base URL of an OpenAI-compatible gateway such as hikyaku (http://hikyaku:8080/v1). | | `gateway_api_key` | string | GatewayAPIKey authenticates to an external gateway. | | `tiers` | map of objects | Tiers map a tier name (fast, strong) to a model. Initial values only: managed in the dashboard after install. | | `budgets` | object | Budgets are initial values only. | | `embedder` | object | Embedder is the embedding model of team memory. Without one, memory search falls back to Postgres full-text search. | | `providers` | object | | | `recordings` | string | Recordings is the directory of recorded responses the mock provider replays. KOJO_LIVE_MODELS=1 ignores it and calls the real providers. | The embedded gateway: Anthropic for both tiers, fallbacks tried in order when a tier's model fails, prices so that the budgets count, a rate limit per tier, and an embedder for team memory. ```yaml models: gateway: embedded providers: anthropic: api_key: "${ANTHROPIC_API_KEY}" openai: api_key: "${OPENAI_API_KEY}" googleai: api_key: "${GEMINI_API_KEY}" tiers: fast: provider: anthropic model: claude-haiku-5-5 price: input_per_mtok: 0.10 output_per_mtok: 0.50 requests_per_minute: 120 fallbacks: - provider: openai model: gpt-6.2-sol strong: provider: anthropic model: claude-opus-5-5 price: input_per_mtok: 4 output_per_mtok: 20 requests_per_minute: 30 fallbacks: - provider: anthropic model: claude-sonnet-5-5 - provider: openai model: gpt-6.2-astra budgets: per_session_usd: 10 per_day_usd: 200 embedder: provider: googleai model: gemini-embedding-2 ``` Azure OpenAI or Microsoft Foundry through the v1 API. A tier's model is the name you gave a deployment, here deployments of gpt-6.2-sol, gpt-6.2-astra and text-embedding-3-large. Leave out api_key to sign in with Microsoft Entra ID instead (a managed identity, AKS workload identity, a service principal). ```yaml models: gateway: embedded providers: azure: endpoint: https://acme-ai.openai.azure.com api_key: "${AZURE_OPENAI_API_KEY}" tiers: fast: provider: azure model: kojo-fast strong: provider: azure model: kojo-strong budgets: per_session_usd: 10 per_day_usd: 200 embedder: provider: azure model: kojo-embeddings ``` Amazon Bedrock through the Converse API. There is no AWS key here: credentials come from the AWS SDK's default chain (environment, shared config files, EKS IRSA or Pod Identity, the instance role). A model is a Bedrock inference profile ID: Anthropic's models need one, such as us.anthropic.claude-opus-5-5. ```yaml models: gateway: embedded providers: bedrock: region: us-east-1 tiers: fast: provider: bedrock model: us.anthropic.claude-haiku-5-5 strong: provider: bedrock model: us.anthropic.claude-opus-5-5 fallbacks: - provider: bedrock model: us.anthropic.claude-sonnet-5-5 budgets: per_session_usd: 10 per_day_usd: 200 embedder: provider: bedrock model: amazon.titan-embed-text-v2:0 ``` An external OpenAI-compatible gateway. It routes on the model name alone, so a tier names no provider. ```yaml models: gateway: http://hikyaku:8080/v1 gateway_api_key: "${MODEL_GATEWAY_API_KEY}" tiers: fast: model: claude-haiku-5-5 strong: model: claude-opus-5-5 fallbacks: - model: claude-sonnet-5-5 budgets: per_session_usd: 10 per_day_usd: 200 ``` Gemini on Vertex AI, with Application Default Credentials: a key file named by GOOGLE_APPLICATION_CREDENTIALS, a gcloud login, or GKE Workload Identity. No key is in this file. ```yaml models: gateway: embedded providers: vertexai: project: acme-models location: global tiers: fast: provider: vertexai model: gemini-4-hydrogen strong: provider: vertexai model: gemini-4-carbon budgets: per_session_usd: 10 per_day_usd: 200 embedder: provider: vertexai model: gemini-embedding-2 ``` #### `models.tiers` | Key | Type | Description | |---|---|---| | `provider` | string | | | `model` | string | | | `fallbacks` | list of objects | Fallbacks are tried in order when the tier's model fails. | | `price` | object | Price is what the model costs, in USD per million tokens. kōjō ships no price table: without a price a tier's calls cost 0 and the USD budgets cannot bound them (kojo doctor warns). The tier's fallbacks are priced the same. | | `requests_per_minute` | integer | RequestsPerMinute rate-limits the tier, per kōjō replica. Zero means no limit. | #### `models.tiers.fallbacks` | Key | Type | Description | |---|---|---| | `provider` | string | Provider is anthropic, openai, googleai, vertexai, azure, bedrock, openrouter, ollama or mock. Anything else (vLLM, LiteLLM) is reached through the openai provider's base_url or an external gateway. | | `model` | string | Model is the provider's model ID. With azure it is the name of a deployment, not of a model. | #### `models.tiers.price` | Key | Type | Description | |---|---|---| | `input_per_mtok` | number | | | `output_per_mtok` | number | | #### `models.budgets` | Key | Type | Description | |---|---|---| | `per_session_usd` | number | | | `per_day_usd` | number | | | `per_month_usd` | number | PerMonthUSD caps the whole install's spend since the first of the calendar month, 00:00 UTC. | #### `models.embedder` | Key | Type | Description | |---|---|---| | `provider` | string | Provider is anthropic, openai, googleai, vertexai, azure, bedrock, openrouter, ollama or mock. Anything else (vLLM, LiteLLM) is reached through the openai provider's base_url or an external gateway. | | `model` | string | Model is the provider's model ID. With azure it is the name of a deployment, not of a model. | #### `models.providers` | Key | Type | Description | |---|---|---| | `anthropic` | object | | | `openai` | object | | | `googleai` | object | GoogleAI is Gemini through the Gemini API, with an API key. | | `vertexai` | object | VertexAI is Gemini through Google Cloud's Vertex AI, with Google Cloud credentials. | | `azure` | object | Azure is Azure OpenAI or Microsoft Foundry. | | `bedrock` | object | Bedrock is Amazon Bedrock. | | `openrouter` | object | | | `ollama` | object | | #### `models.providers.anthropic` | Key | Type | Description | |---|---|---| | `api_key` | string | | #### `models.providers.openai` | Key | Type | Description | |---|---|---| | `api_key` | string | | | `base_url` | string | | #### `models.providers.googleai` | Key | Type | Description | |---|---|---| | `api_key` | string | | #### `models.providers.vertexai` | Key | Type | Description | |---|---|---| | `project` | string | Project is the Google Cloud project ID. Default GOOGLE_CLOUD_PROJECT. | | `location` | string | Location is a region (us-central1), a multi-region (us, eu) or global. Default GOOGLE_CLOUD_LOCATION, then GOOGLE_CLOUD_REGION. | | `base_url` | string | BaseURL replaces the endpoint derived from the location, such as a Private Service Connect endpoint. Requests keep the project and location in their path. | #### `models.providers.azure` | Key | Type | Description | |---|---|---| | `endpoint` | string | Endpoint is the resource's endpoint, such as https://acme.openai.azure.com (Azure OpenAI) or https://acme.services.ai.azure.com (Microsoft Foundry). Default AZURE_OPENAI_ENDPOINT. | | `api_key` | string | APIKey is a key of the resource. Default AZURE_OPENAI_API_KEY. Without one, kōjō uses Entra ID. | #### `models.providers.bedrock` | Key | Type | Description | |---|---|---| | `region` | string | Region is the AWS region, such as us-east-1. Default AWS_REGION, then AWS_DEFAULT_REGION. | | `profile` | string | Profile names a profile of the shared AWS config files. Default AWS_PROFILE, then the default profile. | | `endpoint` | string | Endpoint replaces the region's Bedrock Runtime endpoint, such as a VPC interface endpoint. | #### `models.providers.openrouter` | Key | Type | Description | |---|---|---| | `api_key` | string | | #### `models.providers.ollama` | Key | Type | Description | |---|---|---| | `url` | string | URL defaults to http://localhost:11434. | ### `sandbox` | Key | Type | Description | |---|---|---| | `driver` | string | Driver is sbx, k8s or e2b. docker and fake exist for development and need dev: true. | | `sbx` | object | | | `k8s` | object | | | `e2b` | object | | | `docker` | object | | | `proxy` | object | | | `ttl` | string | TTL is how long a sandbox may live. Default 4h. A question to open a pull request (merge policy ask) closes no later than 30 minutes before the sandbox that holds the change expires; without an answer the change becomes a draft. | | `image` | string | Image is the sandbox image of kits that name none. Default: the kojo-toolchain image of this release. | | `max_resources` | object | MaxResources is the most CPU, memory and disk any kit gets, in Kubernetes quantity syntax ({cpu: "2", memory: 4Gi, disk: 20Gi}). A kit that asks for more gets this much instead, and the driver logs it; a kit that asks for less, or names no quantity, is unchanged. It fits kits to smaller machines: the built-in kits ask for up to 8 CPUs and 16Gi. Empty: no cap. The docker driver also lowers a request to what the Docker daemon has; the e2b driver sends no kit resources. | Docker Sandboxes on a single VM. `driver: sbx` alone uses the `sbx` on the PATH and the default kits directory; the other keys override the defaults. ```yaml sandbox: driver: sbx sbx: binary: /usr/local/bin/sbx kits_dir: /var/lib/kojo/sbx-kits ttl: 2h ``` An E2B-compatible service (E2B Cloud here): every session in a microVM the service runs, created from a template of your own, with kojo-proxy at a public address as the only destination a sandbox may connect to. ```yaml sandbox: driver: e2b e2b: api_key: "${E2B_API_KEY}" template: kojo-toolchain proxy: listen: ":3128" advertise_url: http://203.0.113.7:3128 ttl: 1h ``` Kubernetes Agent Sandbox with Kata Containers, two warm pods per sandbox template, kojo-proxy as a separate deployment of several replicas, and an image of your own for kits that name none. ```yaml sandbox: driver: k8s k8s: namespace: kojo-sandboxes runtime_class: kata warm_pool_size: 2 storage_class: fast-ssd proxy: mode: remote advertise_url: http://kojo-proxy.kojo.svc:3128 # A headless Service: every address it resolves to is one replica. admin_url: http://kojo-proxy-admin.kojo.svc:3129 admin_discovery: dns admin_token: "${KOJO_PROXY_ADMIN_TOKEN}" ca_cert_file: /var/run/kojo/proxy-ca/tls.crt ca_key_file: /var/run/kojo/proxy-ca/tls.key ttl: 4h image: registry.example.com/acme/toolchain:1.4.0 ``` Development only: sandboxes are plain containers, which the `docker` driver refuses without `dev: true`. A separate `kojo proxy` container is the only way out of the sandbox network, and `allow_private` lets it reach a forge on a private address. ```yaml dev: true sandbox: driver: docker docker: network: kojo-dev-sandbox proxy: mode: remote advertise_url: http://kojo-proxy:3128 admin_url: http://kojo-proxy:3129 admin_token: "${KOJO_PROXY_ADMIN_TOKEN}" allow_private: true ttl: 1h ``` #### `sandbox.sbx` | Key | Type | Description | |---|---|---| | `binary` | string | Binary is the sbx CLI. Default "sbx" on PATH. | | `kits_dir` | string | KitsDir is where kōjō writes the kit it generates per skill. | #### `sandbox.k8s` | Key | Type | Description | |---|---|---| | `namespace` | string | Namespace sandboxes run in. Default: kōjō's own namespace. | | `runtime_class` | string | RuntimeClass is kata, gvisor, or a cluster-specific name. | | `warm_pool_size` | integer | WarmPoolSize is the number of pre-warmed pods per template. | | `proxy_image` | string | ProxyImage records the image of kojo-proxy. The binary does not read it: the Helm chart deploys the proxy and writes its image here so the rendered config says what runs. | | `kubeconfig` | string | Kubeconfig is used outside a cluster. Empty means in-cluster config. | | `storage_class` | string | | | `unschedulable_timeout` | string | UnschedulableTimeout is how long a sandbox pod may stay unschedulable (no node has room for its requests) before creating the sandbox fails with the scheduler's reason. It is the time a cluster autoscaler gets to add a node. Default 2m. Starting a sandbox has 5 minutes in all, so a longer value waits at most that long. | #### `sandbox.e2b` | Key | Type | Description | |---|---|---| | `api_key` | string | APIKey authenticates to the service. | | `api_url` | string | APIURL is the service's control API. Default https://api.. | | `domain` | string | Domain is where sandboxes are reachable (-.). Default e2b.app. | | `sandbox_url` | string | SandboxURL is one fixed URL for every sandbox, for a service whose sandbox proxy routes by header instead of by host name (CubeSandbox without a wildcard domain). Default: https://-.. | | `template` | string | Template is the sandbox template used when a skill's kit names no image and sandbox.image is not set. On this driver a kit's image is a template name or ID. | #### `sandbox.docker` | Key | Type | Description | |---|---|---| | `binary` | string | Binary is the docker CLI. Default "docker" on PATH. | | `network` | string | Network is the Docker network sandboxes join. kōjō creates an internal one (no route out except the proxy) when empty. | #### `sandbox.proxy` | Key | Type | Description | |---|---|---| | `mode` | string | Mode is embedded (the proxy runs in the kōjō process) or remote (a separate `kojo proxy` deployment). Default: embedded, and remote for the k8s driver. | | `listen` | string | Listen is the address sandboxes connect to. Default ":3128". | | `advertise_url` | string | AdvertiseURL is the proxy's address as sandboxes see it (http://kojo-proxy.kojo.svc:3128). | | `admin_url` | string | AdminURL is the remote proxy's admin API (http://kojo-proxy:3129). It is one replica, unless admin_discovery is dns. | | `admin_discovery` | string | AdminDiscovery is how kōjō finds the proxy's replicas. Empty: one replica at admin_url, or the replicas of admin_urls. dns: every address the host of admin_url resolves to is a replica, resolved again every 5 seconds; on Kubernetes, a headless Service that publishes replicas before they are ready, as the Helm chart's proxy-admin Service does. Several replicas need ca_cert_file and ca_key_file. | | `admin_urls` | list of strings | AdminURLs are the admin APIs of several replicas, instead of admin_url, for replicas at fixed addresses. | | `sync_timeout` | string | SyncTimeout is how long a `kojo proxy` replica waits, after it starts, for a kōjō server to send it the sandbox policies before it reports ready on /readyz anyway. Until a kōjō server has synced it, a replica is not ready and takes no sandbox traffic. Default 30s. | | `admin_listen` | string | AdminListen is the address of the admin API in `kojo proxy`. Default ":3129". | | `admin_token` | string | AdminToken authenticates the core to the admin API. | | `ca_cert_file` | string | CACertFile and CAKeyFile hold the CA that signs the certificates of hosts the proxy injects credentials on. Generated when empty. | | `ca_key_file` | string | | | `allow_private` | boolean | AllowPrivate lets sandboxes reach every allowlisted host on loopback, link-local and private addresses. It is off by default, which stops a sandbox from using the proxy to reach the cluster's or the cloud's internal services. For a forge on a private network, name it in PrivateHosts instead. | | `private_hosts` | list of strings | PrivateHosts are the hostnames, or "*.domain" patterns, that may resolve to loopback, link-local and private addresses: a forge or a registry on a private network. Every other allowlisted host must still resolve to public addresses only. A host here is reachable only when a sandbox's allowlist names it too. | | `upstream_ca_file` | string | UpstreamCAFile holds extra root certificates (PEM) the proxy trusts when it connects to a host it injects credentials on: a forge with a private CA. | | `max_conns_per_sandbox` | integer | MaxConnsPerSandbox bounds what one sandbox has open through the proxy at once: tunnels, intercepted connections and plain HTTP requests in flight. One more gets HTTP 429, so one sandbox cannot take the connections of the process the proxy runs in from the others. Default 64. | | `idle_timeout` | string | IdleTimeout closes a tunnel through which nothing has gone either way for that long, and a sandbox's keep-alive connection to the proxy that sends no request for that long. Default 5m. | #### `sandbox.max_resources` | Key | Type | Description | |---|---|---| | `cpu` | string | CPU in cores ("4", "0.5") or millicores ("500m"). | | `memory` | string | Memory in bytes with a binary or decimal suffix ("8Gi", "512Mi"). | | `disk` | string | Disk is the size of the workspace ("40Gi"). | ### `defaults` | Key | Type | Description | |---|---|---| | `merge_policy` | string | MergePolicy is draft_only (default), ask or auto_merge. | | `skills_repo` | string | SkillsRepo is the shared repository of org-level skills, as forge/owner/name. It is used when the org's skills are edited in git (seed.skills_source.org). | The org's first merge policy asks for an approval in chat before a pull request is opened ready for review. `skills_repo` is the repository of org-level skills, used when `seed.skills_source.org` is `git`. ```yaml defaults: merge_policy: ask skills_repo: github/acme/factory-skills ``` ### `seed` | Key | Type | Description | |---|---|---| | `skills_source` | object | | | `activation` | object | | Org-level skills are edited in git, in the repository `defaults.skills_repo` names, and activating a skill draft needs an eval with a pass rate of at least 0.7. ```yaml seed: skills_source: org: git repo: git activation: require_eval: true min_eval_pass_rate: 0.7 defaults: skills_repo: github/acme/factory-skills ``` #### `seed.skills_source` | Key | Type | Description | |---|---|---| | `org` | string | Org is dashboard (default) or git. | | `repo` | string | Repo is git (default) or dashboard. | #### `seed.activation` | Key | Type | Description | |---|---|---| | `require_eval` | boolean | | | `min_eval_pass_rate` | number | | ### `telemetry` | Key | Type | Description | |---|---|---| | `otlp_endpoint` | string | OTLPEndpoint is the OTLP/HTTP endpoint traces are exported to: a base URL (http://collector:4318, which gets /v1/traces) or a full URL. The standard OTEL_EXPORTER_OTLP_ENDPOINT variable works too. | | `service_name` | string | ServiceName defaults to kojo. | Traces go to an OpenTelemetry collector over OTLP/HTTP, under a service name of their own. ```yaml telemetry: otlp_endpoint: http://otel-collector.observability.svc:4318 service_name: kojo-production ``` --- > Source: https://xavidop.github.io/kojo/docs/models # Models This page covers how kōjō calls language models: the tiers, the providers of the embedded gateway, an external OpenAI-compatible gateway, fallbacks, rate limits, budgets and prices. Read it when you install kōjō, change a model, or set spend caps. ## How model calls work Every model call goes through one model gateway inside the kōjō process (`internal/models`). A caller names a tier, not a model. The gateway: 1. resolves the tier to a model and its fallbacks, 2. waits if the tier has a requests-per-minute limit, 3. calls the model, and tries the fallbacks in order if the call fails, 4. prices the answer with the tier's configured price. One model call of a session, from the budget check the session makes first to the price: ```mermaid flowchart TD A["A session calls a tier"] --> B{"Session or daily budget reached?"} B -- yes --> X["Refused: budget reached"] B -- no --> C["The tier resolves to its model and fallbacks"] C --> D["Wait for the tier's requests-per-minute slot"] D --> E["Call the tier's model"] E --> F{"Answered?"} F -- yes --> G["Priced with the tier's price, added to the session's cost"] F -- no --> H{"A fallback left?"} H -- yes --> I["Call the next fallback"] I --> F H -- no --> Y["The call fails, with every error joined"] ``` The gateway runs in one of three modes. `kojo doctor` reports the mode next to each tier. | Mode | When | What it calls | |---|---|---| | `embedded` | `models.gateway: embedded` (the default) | The providers, directly, through Genkit Go plugins | | external | `models.gateway` is a URL | One OpenAI-compatible gateway at that URL | | `replay` | `models.recordings` is set, or the tiers use the `mock` provider | Nothing. Recorded responses are replayed | ## Tiers A tier is a name mapped to a model. The tiers `fast` and `strong` are required: kōjō refuses to start without both, because the engine and the built-in skills use them. You may add more tiers under other names and refer to them from a skill. | Caller | Tier | Set by | |---|---|---| | Orchestrator | `strong` | Fixed | | Subagent of a skill | `fast` unless the skill says otherwise | `model_tier` in `SKILL.md` | | Goal critic's judge | `strong` unless the skill says otherwise | `judge.model_tier` in `goals.yaml` | | Risk classifier of the merge policy | `fast` | Fixed. Runs only when the merge policy turns the classifier on | | Natural-language schedule conversion | `fast` | Fixed | | `kojo doctor` check | Every configured tier, one call each | Fixed | A skill that names a tier that is not configured fails at its first model call with `tier "" is not configured`. See [SKILL.md](/docs/skills/skill-md/#front-matter) for `model_tier` and [Merge policy](/docs/merge-policy/) for the risk classifier. Each tier has these keys: | Key | Type | Default | Meaning | |---|---|---|---| | `provider` | string | none | Provider of the model. Required with the embedded gateway, ignored with an external one | | `model` | string | none | Model ID, passed to the provider unchanged. Required | | `fallbacks` | list of `provider` + `model` | empty | Models tried in order when the tier's model fails | | `price.input_per_mtok` | number | none | USD per million input tokens | | `price.output_per_mtok` | number | none | USD per million output tokens | | `requests_per_minute` | integer | `0` (no limit) | Rate limit of the tier | kōjō does not check that a model ID exists. `kojo doctor` sends one short prompt to every tier and fails the tier's check when the model does not answer. ## Boot config and runtime config Model settings live in two places. | Setting | Where | How to change it | |---|---|---| | `models.gateway`, `models.gateway_api_key` | `kojo.yaml` | Edit the file, restart | | `models.providers.*` (API keys, URLs) | `kojo.yaml` or environment | Edit, restart | | `models.embedder` | `kojo.yaml` | Edit the file, restart | | `models.recordings` | `kojo.yaml` | Edit the file, restart | | Tiers (`provider`, `model`, `fallbacks`, `price`, `requests_per_minute`) | Runtime config object `settings/models` | Dashboard, or `kojo config apply` | | Budgets (`per_session_usd`, `per_day_usd`) | Runtime config object `settings/models` | Dashboard, or `kojo config apply` | `models.tiers` and `models.budgets` in `kojo.yaml` are initial values. On the first start kōjō copies them into the runtime object `settings/models`. After that the runtime object is the source of truth, and editing those two keys in `kojo.yaml` changes nothing on a running install. The exception is `kojo eval --local`, which starts from `kojo.yaml` with an in-memory store every time. The runtime object is org-wide: a repository cannot override it. Changing it needs the `operator` role. Every change is a new revision that can be rolled back. In the dashboard it is the **Models & budgets** page under Settings; see [the dashboard](/docs/manage/dashboard/#settings).
The Models and budgets settings page, scrolled down: the strong tier with its provider, model, prices, request limit and fallbacks, the Budgets panel with per-session, per-day and per-month caps, and a history panel with revisions on the right.
The history on the right starts with the value copied from kojo.yaml on the first start; every later change is a revision above it.
A session pins the config revisions it starts with. A tier or budget change applies to sessions that start after it, not to sessions in flight. The runtime object, as `kojo config export` writes it and `kojo config apply` reads it: ```yaml version: 1 objects: - scope: org object: settings/models content: tiers: fast: provider: anthropic model: claude-haiku-5-5 strong: provider: anthropic model: claude-opus-5-5 budgets: per_session_usd: 10 per_day_usd: 200 ``` The full list of `kojo.yaml` keys is in the [kojo.yaml reference](/docs/config-reference/), and the schema is [kojo.schema.json](/schema/kojo.schema.json). ## The embedded gateway With `models.gateway: embedded` kōjō calls the providers itself. The gateway is built on Genkit Go and uses its provider plugins. | Provider | `kojo.yaml` key | Environment variable | Loaded when | |---|---|---|---| | `anthropic` | `models.providers.anthropic.api_key` | `ANTHROPIC_API_KEY` | A key is set | | `openai` | `models.providers.openai.api_key`, `models.providers.openai.base_url` | `OPENAI_API_KEY`, `OPENAI_BASE_URL` | A key or a base URL is set | | `googleai` | `models.providers.googleai.api_key` | `GEMINI_API_KEY`, then `GOOGLE_API_KEY` | A key is set | | `vertexai` | `models.providers.vertexai.project`, `.location`, `.base_url` | `GOOGLE_CLOUD_PROJECT`; `GOOGLE_CLOUD_LOCATION`, then `GOOGLE_CLOUD_REGION` | A project and a location are set and Google Cloud credentials are found | | `azure` | `models.providers.azure.endpoint`, `.api_key` | `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_API_KEY` | An endpoint is set | | `bedrock` | `models.providers.bedrock.region`, `.profile`, `.endpoint` | `AWS_REGION`, then `AWS_DEFAULT_REGION` | A region is set and the AWS configuration loads | | `openrouter` | `models.providers.openrouter.api_key` | `OPENROUTER_API_KEY` | A key is set | | `ollama` | `models.providers.ollama.url` (default `http://localhost:11434`) | none | Always | A value in `kojo.yaml` wins over the environment variable. With the compose install the keys come from `.env`; with the Helm chart they come from the Secret named by `secrets.existingSecret`. See [Deploy](/docs/deploy/). `vertexai`, `azure` without a key, and `bedrock` take their credentials from the cloud's usual sources instead; their sections below say which. In `kojo.yaml` the provider name of a tier must be one of the eight above, or `mock` (see [the replay provider](/docs/models/#the-replay-provider)); the file is rejected otherwise. A tier changed at runtime is only checked for a non-empty `model`, so a wrong provider name there shows up at call time and in `kojo doctor`. A provider that is not set up is not a startup error, whether its key, a setting or its credentials are missing. A tier's model whose provider is not set up is skipped at call time. When no model of the tier is usable, the call fails with `provider ` and the reason, such as `has no API key configured` or `has no region configured`. Run `kojo doctor` after changing keys, credentials or tiers. The `openai` provider also serves any OpenAI-compatible server: set `base_url` to it. When a base URL is set and no key is, kōjō sends no `Authorization` header. Use this, or an external gateway, for vLLM, LiteLLM and other providers that have no entry in the table. The `openai` and `azure` providers call the Chat Completions API and pass the tools there, so a tier's model must take function calls through it. OpenAI's model pages say which do not: `gpt-6-luna` takes them only with `reasoning_effort` set to `none`, which kōjō does not set, and `gpt-6.1-terra` takes tools through the Responses API only. `gpt-6.2-astra` and `gpt-6.2-sol` take them. ### One provider ```yaml server: public_url: "${KOJO_PUBLIC_URL}" auth: session_secret: "${KOJO_SESSION_SECRET}" tokens: - name: admin token: "${KOJO_ADMIN_TOKEN}" role: admin database: url: "${DATABASE_URL}" models: gateway: embedded providers: anthropic: api_key: "${ANTHROPIC_API_KEY}" tiers: fast: provider: anthropic model: claude-haiku-5-5 price: input_per_mtok: 0.10 output_per_mtok: 0.50 strong: provider: anthropic model: claude-opus-5-5 price: input_per_mtok: 4 output_per_mtok: 20 budgets: per_session_usd: 10 per_day_usd: 200 sandbox: driver: sbx ``` The prices in this example are placeholders. Replace them with the prices of your provider's price list. The `providers` block is optional here: without it kōjō reads `ANTHROPIC_API_KEY` from the environment. ### Two providers with fallback ```yaml server: public_url: "${KOJO_PUBLIC_URL}" auth: session_secret: "${KOJO_SESSION_SECRET}" tokens: - name: admin token: "${KOJO_ADMIN_TOKEN}" role: admin database: url: "${DATABASE_URL}" models: gateway: embedded providers: anthropic: api_key: "${ANTHROPIC_API_KEY}" openai: api_key: "${OPENAI_API_KEY}" tiers: fast: provider: anthropic model: claude-haiku-5-5 requests_per_minute: 120 fallbacks: - provider: openai model: gpt-6.2-sol strong: provider: anthropic model: claude-opus-5-5 requests_per_minute: 30 fallbacks: - provider: openai model: gpt-6.2-astra budgets: per_session_usd: 10 per_day_usd: 200 sandbox: driver: sbx ``` ### Local Ollama ```yaml server: public_url: "${KOJO_PUBLIC_URL}" auth: session_secret: "${KOJO_SESSION_SECRET}" tokens: - name: admin token: "${KOJO_ADMIN_TOKEN}" role: admin database: url: "${DATABASE_URL}" models: gateway: embedded providers: ollama: url: http://localhost:11434 tiers: fast: provider: ollama model: nemotron-3.5-lightning:30b strong: provider: ollama model: qwen3.8:27b budgets: per_session_usd: 10 per_day_usd: 200 sandbox: driver: sbx ``` Pull the models into Ollama first. Pick models that support tool calling: the orchestrator and the subagents work through tool calls. No API key is needed, and no provider is contacted outside your network. The tiers above have no price, so every call costs 0 USD and the budgets never trigger; see [prices and cost](/docs/models/#prices-and-cost). kōjō does not set the Genkit Ollama plugin's request timeout, so the plugin's default of 30 seconds per request applies. ### Gemini on Vertex AI `vertexai` calls Gemini through Google Cloud's Vertex AI, with Google Cloud credentials instead of a Gemini API key. `googleai` stays the provider for an API key. ```yaml models: gateway: embedded providers: vertexai: project: acme-models location: global tiers: fast: provider: vertexai model: gemini-4-hydrogen strong: provider: vertexai model: gemini-4-carbon budgets: per_session_usd: 10 per_day_usd: 200 ``` This fragment goes inside a complete `kojo.yaml`. | Key | Default | Meaning | |---|---|---| | `project` | `GOOGLE_CLOUD_PROJECT` | The Google Cloud project ID. | | `location` | `GOOGLE_CLOUD_LOCATION`, then `GOOGLE_CLOUD_REGION` | A region such as `us-central1`, a multi-region (`us`, `eu`) or `global`. | | `base_url` | derived from the location | Another endpoint, such as a Private Service Connect endpoint. Requests keep the project and the location in their path. | kōjō calls the Vertex AI API at version `v1beta1`, the version Genkit's plugin is written against, whatever the genai SDK's default or `GOOGLE_GENAI_API_VERSION` says. A model is a Gemini model ID; the provider serves Google's own models, not the partner models of the Model Garden. The credentials are Google's Application Default Credentials, looked up when kōjō starts: - **One VM**: a service account key file named by `GOOGLE_APPLICATION_CREDENTIALS`, or `gcloud auth application-default login` for the user kōjō runs as. On a Compute Engine VM, the VM's service account through the metadata server. - **GKE**: Workload Identity Federation for GKE. Grant the Kubernetes service account of the kōjō pods a role that may call Vertex AI, such as `roles/aiplatform.user`, or link it to an IAM service account that has one with the annotation `iam.gke.io/gcp-service-account` (`serviceAccount.annotations` in the [Helm chart](/docs/deploy/helm/#model-provider-credentials)). Without credentials the provider is not set up, and its models fail with `found no Google Cloud credentials`. ### Azure OpenAI and Microsoft Foundry `azure` calls an Azure OpenAI or Microsoft Foundry resource through its OpenAI-compatible v1 API, at `/openai/v1/`, with Genkit's OpenAI-compatible plugin. A tier's model is the name of a deployment, which you choose when you deploy a model, not the model's ID: kōjō sends it as the request's `model`. The v1 API needs no `api-version`. ```yaml models: gateway: embedded providers: azure: endpoint: https://acme-ai.openai.azure.com api_key: "${AZURE_OPENAI_API_KEY}" tiers: fast: provider: azure model: kojo-fast # your deployment of gpt-6.2-sol strong: provider: azure model: kojo-strong # your deployment of gpt-6.2-astra budgets: per_session_usd: 10 per_day_usd: 200 ``` This fragment goes inside a complete `kojo.yaml`. | Key | Default | Meaning | |---|---|---| | `endpoint` | `AZURE_OPENAI_ENDPOINT` | `https://.openai.azure.com` for Azure OpenAI, or `https://.services.ai.azure.com` for Microsoft Foundry. An endpoint that already ends in `/openai/v1` is used as it is. It must be `https`, except on a loopback host. | | `api_key` | `AZURE_OPENAI_API_KEY` | A key of the resource, sent in the `api-key` header. Without one, kōjō uses Microsoft Entra ID. | Without a key, kōjō gets a Microsoft Entra ID token for the scope `https://ai.azure.com/.default` and sends it as a bearer token, fetching a new one shortly before it expires. The token comes from the Azure SDK's `DefaultAzureCredential`, which tries in order: a service principal in the environment (`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, and `AZURE_CLIENT_SECRET` or a certificate), workload identity, a managed identity, and the Azure CLI, Azure Developer CLI and Azure PowerShell logins. The identity needs a role on the resource that may call its deployments, such as Cognitive Services OpenAI User. - **One VM**: the key in `.env`; or, on an Azure VM, its managed identity; or `az login` for the user kōjō runs as. - **AKS**: the key in the Secret named by `secrets.existingSecret`; or Microsoft Entra Workload ID, with the service account annotation `azure.workload.identity/client-id` and the pod label `azure.workload.identity/use: "true"` (see the [Helm chart](/docs/deploy/helm/#model-provider-credentials)). ### Amazon Bedrock `bedrock` calls Amazon Bedrock's Converse API with the AWS SDK for Go, through the community Genkit plugin [genkit-aws-bedrock-go](https://github.com/xavidop/genkit-aws-bedrock-go). A model is a Bedrock model ID, an inference profile ID such as `us.anthropic.claude-opus-5-5`, or an inference profile ARN. Anthropic's models need an inference profile ID (a `global.`, `us.` or other regional prefix before the model ID): Bedrock refuses their bare model IDs for on-demand use in most regions. ```yaml models: gateway: embedded providers: bedrock: region: us-east-1 tiers: fast: provider: bedrock model: us.anthropic.claude-haiku-5-5 strong: provider: bedrock model: us.anthropic.claude-opus-5-5 budgets: per_session_usd: 10 per_day_usd: 200 ``` This fragment goes inside a complete `kojo.yaml`. | Key | Default | Meaning | |---|---|---| | `region` | `AWS_REGION`, then `AWS_DEFAULT_REGION` | The AWS region. | | `profile` | `AWS_PROFILE`, then the default profile | A profile of the shared AWS config files. | | `endpoint` | the region's Bedrock Runtime endpoint | Another endpoint, such as a VPC interface endpoint. | `kojo.yaml` holds no AWS key. The credentials come from the AWS SDK's default chain: the environment (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`), the shared config and credentials files (including SSO profiles), web identity (`AWS_ROLE_ARN` and `AWS_WEB_IDENTITY_TOKEN_FILE`), the container credentials of ECS and EKS Pod Identity, and the EC2 instance role. They are fetched at the first call, not at start. A Bedrock API key in `AWS_BEARER_TOKEN_BEDROCK` is used instead of the chain; the SDK sends it over https only. The identity needs `bedrock:InvokeModel` on the models the tiers name. - **One VM**: on EC2, the instance role; elsewhere, a profile in `~/.aws/config` of the user kōjō runs as, or the variables above in `.env`. - **EKS**: IAM roles for service accounts, with the service account annotation `eks.amazonaws.com/role-arn`; or EKS Pod Identity, with an association between the role and the kōjō pods' service account, which needs no annotation (see the [Helm chart](/docs/deploy/helm/#model-provider-credentials)). Each Bedrock call times out after 10 minutes; kōjō sets this, because the plugin's default of 30 seconds is shorter than a long answer takes. kōjō sets no maximum on the answer's length, so the plugin asks Claude models for at most 4,096 output tokens (8,192 for some Claude 3.5 to 4 models it recognizes by name). Genkit's Anthropic plugin uses 4,096 for the `anthropic` provider as well. ## An external gateway Set `models.gateway` to the base URL of an OpenAI-compatible gateway and kōjō sends every model call there instead of to the providers. hikyaku is one such gateway. The URL is the API base, including a path such as `/v1` when the gateway serves under one. ```yaml server: public_url: "${KOJO_PUBLIC_URL}" auth: session_secret: "${KOJO_SESSION_SECRET}" tokens: - name: admin token: "${KOJO_ADMIN_TOKEN}" role: admin database: url: "${DATABASE_URL}" models: gateway: http://hikyaku:8080/v1 gateway_api_key: "${MODEL_GATEWAY_API_KEY}" tiers: fast: model: claude-haiku-5-5 strong: model: claude-opus-5-5 fallbacks: - model: gpt-6.2-astra budgets: per_session_usd: 10 per_day_usd: 200 sandbox: driver: sbx ``` With an external gateway: - The gateway routes on the model name alone. `provider` in a tier or a fallback is not validated and not sent. - `models.gateway_api_key` is sent as a bearer token. Without it kōjō sends no `Authorization` header. - `models.providers.*` and the provider environment variables are not read. - Tiers, fallbacks, requests-per-minute limits, prices and budgets still work in kōjō as described on this page. A fallback is another model name sent to the same gateway. - `kojo doctor` shows the gateway URL as the mode. ## Fallbacks `fallbacks` is an ordered list of models for a tier. When a call to the tier's model returns an error, kōjō logs a warning and sends the same request to the next model in the list. It stops at the first model that answers. When all fail, the call fails with every error joined. - Any error triggers the fallback: there is no distinction between a rate limit, an outage and a bad request. - A cancelled or timed-out session does not try the remaining models. - The step in the session records the model that answered, as `provider/model`. - A tier has one price. A fallback's calls are priced with the tier's price, not its own. ## Requests-per-minute limits `requests_per_minute` spaces the calls of a tier: with a limit of 60, calls to that tier start at least one second apart. A call that arrives early waits its turn. Nothing is rejected. - The limit is per tier and is shared by every session of the process. - It is kept in memory, per process. With several replicas, each replica applies the limit on its own, so the total rate is the limit times the number of replicas. - One wait covers a call and its fallbacks. - `0` or no value means no limit. ## Budgets `settings/models` holds three spend caps, all in USD. A value of `0` or no value turns that cap off. | Key | Scope | Checked | |---|---|---| | `budgets.per_session_usd` | One session | Before every model call of the session, against the session's cost so far | | `budgets.per_day_usd` | The whole install | Before every model call of every session, against the cost of all model calls started in the last 24 hours | | `budgets.per_month_usd` | The whole install | Before every model call of every session, against the cost of all model calls started since the first of the calendar month, 00:00 UTC | Teams, repositories, skills and people have limits of their own in `settings/limits`: daily and monthly spend, and how many sessions run at once. See [Limits per team and repository](#limits-per-team-and-repository) and [Limits per skill and person](#limits-per-skill-and-person). The caps are checked before a call, so a session can pass a cap by the cost of one call. The daily cap is a rolling 24-hour window, not a calendar day, and it counts every session, including evals run on the server. The monthly cap is checked after the daily one. It does not replace it: a monthly cap alone does not stop one bad day from spending the month, so `kojo doctor` still asks for a per-session or per-day cap. When a running session reaches a cap, or a limit of its team, repository or requester: 1. The model call is refused with `budget reached` and the amounts. 2. The session stops working. It is not retried. 3. kōjō still delivers what exists, with a report that says the budget was reached. A change that was already made goes through the merge policy as a result that did not pass. 4. The session ends with status `failed`, and its error is the budget message. A skill's limit is the exception: it stops only that skill's subagent, and the session goes on without it (see [Skills](#skills)). A session that has not started waits while the daily or monthly cap, or a limit of its team, repository, requester, or the skill it was started for, is spent. It stays `queued` and is looked at again 10 minutes later, until the spend is back under every limit it counts against. A session that is already running stops at its next model call, as above. The per-session cap never makes a session wait. Budgets only bound what has a price. `kojo doctor` fails its `budgets` check when neither the per-session nor the per-day cap is set, and warns when a tier has no price. The Helm chart's default config sets `per_session_usd: 10` and `per_day_usd: 200`, with two tiers that have no price. On a default chart install the caps therefore bound nothing, and `kojo doctor` warns about it, until you set a price on each tier. ## Limits per team and repository On an install that several teams share, the install-wide caps let one team or one repository spend the whole daily budget, and take every worker. The `settings/limits` object bounds each team and each repository on its own. Only an `admin` changes it; its keys, validation and an example are in [Runtime config objects](/docs/manage/objects/#settingslimits). | Limit | Key | What it bounds | |---|---|---| | Daily spend | `per_day_usd` | The cost of the model calls started in the last 24 hours, a rolling window like the install's daily cap | | Monthly spend | `per_month_usd` | The cost of the model calls started since the first of the calendar month, 00:00 UTC | | Running sessions | `max_running` | How many sessions run at once | Each of them can be set under `teams.` and under `repos.`. `triggers..max_running` caps the running sessions of one trigger, the kind of request that started them: `eval`, `schedule`, `mention` and so on. A trigger has no spend limit. ### Teams A team is a team of the [`rbac` object](/docs/manage/objects/#rbac). Its `repos` key lists the repositories the team owns, and a repository belongs to one team at most. Owning a repository does not narrow the team's roles: roles hold on every repository. A session counts against its repository, that repository's team, and the install, and against its skills and its requester as [below](#limits-per-skill-and-person). A team's spend is the spend of the repositories `rbac` lists for it now, so a repository moved to another team takes its spend of the window with it. A session with no repository, such as a chat request that names none, counts against no team or repository. - **Evals.** A fixture eval (`kojo eval `, trigger `eval`) has no repository: it counts against the install and the `eval` trigger's cap. An [eval from a repository's history](/docs/evals/#evals-from-your-own-history) runs its sessions on that repository, so they count against it and its team. A skill test started from the dashboard counts against the repository it was given, if any. - **Schedules.** Each session a schedule starts runs on one repository and counts against it and its team, like any other session. `triggers.schedule.max_running` caps scheduled sessions together. ### Spend limits A spend limit works as the install's daily cap does. Before every model call, the cost of the window is summed from the cost recorded on each model step, by the repository of the step's session. When a limit the session counts against is spent, the call is refused with `budget reached` and a message that names the limit, for example `team platform spent $50.10 in the last 24h, its daily limit is $50.00`, and the session stops as described under [Budgets](#budgets). A session that has not started waits in the queue instead, and is looked at again every 10 minutes. The install's daily cap is checked first, then its monthly cap, then the team's limits, the repository's, the skill's and the person's (see [Order of the checks](#order-of-the-checks)). ### Running sessions `max_running` is applied when a worker takes a session from the queue. A queued session whose repository, team or trigger already has as many running sessions as its cap is passed over: it stays `queued`, keeps its place, and starts when one of those sessions ends or waits. A waiting session whose approval was answered, or whose pull request's checks are due a look, is held the same way. A session whose worker died is resumed whatever the caps say, because it already counts as running. Sessions waiting for an approval or for checks do not count: they hold no worker. With several replicas, workers take sessions from the queue one at a time while a cap is set, so a cap holds across every replica. A cap at or above the number of workers holds nothing back on one replica; `kojo doctor` says so. ### Changes and visibility Limits, and the teams of `rbac`, are read when they are checked. A session does not keep the limits it started with: a lower limit stops a running session at its next model call. - The dashboard's Overview shows the install, each team, repository, skill and person with its spend over 24 hours and over the month, its running sessions, and its limits. A queued session that a limit holds back says which limit in the session list and on its page. - `GET /api/v1/limits` and the MCP tool `kojo_limits` return the same. `GET /api/v1/sessions` and `GET /api/v1/sessions/{id}` add `held` to a session a limit holds back. See the [HTTP API](/docs/manage/api/#limits). - `kojo doctor` warns about limits that can never hold anything back: limits of a team that `rbac` does not define or that owns no repository, of a repository that is not enabled, a cap that is not below this replica's workers, and a limit that a tighter one is always reached before. - `kojo limits` prints the same from a terminal, and `kojo limits set` and `unset` change them (see [the CLI](/docs/manage/cli/#limits)). - Prometheus counts sessions put back in the queue by a spent budget (`kojo_budget_waits_total`) and model calls refused by one (`kojo_budget_stops_total`). ## Limits per skill and person `settings/limits` also bounds what one skill and one person may spend, and how many sessions one person runs at once. The keys are `skills.` (`per_day_usd`, `per_month_usd`) and `people.` (`per_day_usd`, `per_month_usd`, `max_running`), with the windows of the table above. ```yaml skills: fix-bug: {per_day_usd: 20, per_month_usd: 300} people: default: {per_day_usd: 10, max_running: 2} alice@example.com: {} token:ci-nightly: {per_day_usd: 40, max_running: 4} ``` ### Skills A skill's spend is the cost of its subagent's model calls, its judge's (the goal critic) and its plan's, in every session and every repository. The orchestrator's calls belong to no skill. Dry runs (skill tests, evals) and self-improvement sessions neither count against a skill's limit nor are stopped by it, so testing a skill never spends its budget. A skill over its limit stops only its own subagent: - Before a subagent starts, and before each of its model calls, its skill's limits are checked. A spent limit refuses the call with `budget reached: skill fix-bug spent $20.10 in the last 24h, its daily limit is $20.00`. - That skill's result fails, with the limit as its reason, and the orchestrator is told the skill stopped. The session goes on with other skills. A later delegation to the skill in that session is checked again and stops at once while the limit is still spent. A skill found over its limit when its plan would be written is not planned, and stays stopped for the rest of the session. - The session's result then does not pass, so it publishes at most a draft pull request of the changes that exist, and ends `failed` with the stop as its reason. A session whose request names a skill (`kojo run --skill`, a schedule's skill, a repository's `auto` skill) waits in the queue while that skill is spent, as it would for a team. A session that names no skill does not wait: its skill is not known until the orchestrator delegates. Skills have no `max_running`, and `settings/limits` refuses one: most sessions are not known to belong to a skill when a worker takes them from the queue, so a claim cannot count them. ### People A session counts against the person who asked for it: | Request | Person | |---|---| | A mention on an issue or pull request | Its author | | A chat message | Its author | | A run from the dashboard, the CLI, the API or MCP | Who signed in, or the API token (`token:`) | | A campaign's sessions | The campaign's creator | | A ticket in a tracker | Who assigned, labelled or mentioned it | Events nobody asked for (a new issue, a new pull request, a push, a failed check), schedules, alerts, feedback and self-improvement sessions count against no one. The person is worked out when the request is accepted and recorded on the session. A key is a person as kōjō records them, in lower case: an email (`alice@example.com`, without `email:`), or `:` when the surface gives no email (`github:alice`, `slack:u02abcdef`, `token:ci-nightly`). A login that `settings/memory.identities` links to an email is recorded as that email, so its entry is the email's. Changing identities later does not move sessions or spend already recorded under the old key. `people.default` applies to everyone without an entry of their own. A person's entry replaces it as a whole: `alice@example.com: {}` has no limit at all, while an entry that sets only `per_day_usd` leaves that person's month and running sessions unbounded. Without `default`, a person without an entry has no limit. A person's cap on running sessions is applied when a worker takes a session from the queue, under the same lock as the other caps, so it holds across replicas. What a person spends is private. A held session, a stopped session and a pull request description say `its requester's daily limit was reached` or `its requester's running-session limit`, never the person or the amounts. `GET /api/v1/limits` lists people only to the `operator` role and up. ### Order of the checks Before every model call, and before a queued session starts, the limits a session counts against are checked in this order. The first spent one is the one named. ```mermaid flowchart LR A[Install, last 24 hours] --> B[Install, this month] B --> C[Team] C --> D[Repository] D --> E[Skill] E --> F[Person] ``` Each of team, repository, skill and person is checked for the day, then the month. The skill is the one whose subagent, judge or plan makes the call, or for a queued session the skill it was started for. ### Seeing and changing them - The dashboard's Overview lists the install, each team, repository, skill and person with its spend and limits; people only for operators. `/settings/limits` edits them. - `GET /api/v1/limits` and the MCP tool `kojo_limits` return the same, with `skills`, `people`, `people_default` and `install.per_month_usd` (see the [HTTP API](/docs/manage/api/#limits)). - `kojo limits`, `kojo limits set` and `kojo limits unset` read and change them from a terminal (see [the CLI](/docs/manage/cli/#limits)). - `kojo doctor` warns about a skill limit no scope resolves, a person key whose namespace is not a surface of the install, a login that identities link to an email, a person allowed more than `people.default`, and an install whose daily cap is not below its monthly cap. - `kojo_budget_waits_total` and `kojo_budget_stops_total` count with `limit="skill"` and `limit="person"`.
The Limits settings page, scrolled to the Skills panel with daily and monthly limits for build-feature and fix-bug, and the People panel with an Everyone else row of 10 dollars a day and 2 running sessions and an entry for ana@acme.test, next to the history of revisions.
Limits per skill and per person under Settings, Limits.
## Prices and cost kōjō ships no price table. A price is configured per tier, in USD per million tokens, and you keep it in step with your provider's price list. The cost of a call is: ```text cost_usd = (tokens_in * input_per_mtok + tokens_out * output_per_mtok) / 1000000 ``` The token counts are the ones the provider reports for the call. A tier without a `price` costs 0 USD per call: its calls are recorded with their tokens, add nothing to the session's cost and are not capped by the budgets. For a local model, set a notional price if you want the budgets to limit token use. Where cost shows up: | Place | What | |---|---| | Each model step of a session | Model that answered, tokens in, tokens out, cost | | The session | Total cost and tokens, in `kojo sessions list`, `kojo sessions show` and the dashboard | | `kojo run` | Cost and tokens on the last line, when the cost is above 0 | | Dashboard overview | Cost of the last 24 hours against the daily budget, and of the last 7 days; each team's and repository's cost over 24 hours and over the month against its limits | | `kojo eval` report | Cost per case and per run | | Audit log | `cost_usd` in the `session.end` entry | | Prometheus | `kojo_model_cost_usd_total` (labels `tier`, `model`) and `kojo_model_tokens_total` (labels `tier`, `model`, `direction`) | See [Prometheus metrics](/docs/observability/metrics/) for the metrics and [Observability](/docs/observability/#session-replay) for session replay. ## Embedder `models.embedder` names the embedding model of team memory, as a `provider` and a `model`. Without one, and whenever an embedding call fails, memory search uses Postgres full-text search. See [Skills](/docs/skills/) for memory. | Provider | Embedding models | |---|---| | `googleai`, `vertexai` | `gemini-embedding-2`; `gemini-embedding-001` | | `openai` | `text-embedding-3-large`, `text-embedding-3-small` | | `azure` | Your deployment of `text-embedding-3-large` or `text-embedding-3-small`, by its deployment name | | `bedrock` | Amazon Titan Text Embeddings V2 (`amazon.titan-embed-text-v2:0`) and Cohere Embed v3 (`cohere.embed-english-v3`, `cohere.embed-multilingual-v3`): the embedding models the Bedrock plugin supports | `openrouter` and `ollama` have no embedder in kōjō: their Genkit plugins register none by name, so an embedder on either fails and memory search uses full-text search. ```yaml models: embedder: provider: googleai model: gemini-embedding-2 ``` This fragment goes inside the `models` block of `kojo.yaml`. ## The replay provider The replay provider answers model calls from recorded responses. It needs no network and no API key. The dev stacks, the end-to-end tests and the skill evals in CI run on it. See [Recordings](/docs/development/testing/#recordings) and [Evals](/docs/evals/). Replay is on when either of these is true: - `models.recordings` names a directory and `KOJO_LIVE_MODELS` is not `1`. - The tiers use the `mock` provider. Then `models.recordings` is required, every tier must be `mock`, and `KOJO_LIVE_MODELS=1` has no effect. kōjō logs a warning at start when it replays, and `kojo doctor` warns that no real model is called. ### Recordings `models.recordings` is a directory. Every `.yaml` and `.yml` file under it, at any depth, is a list of recordings: ```yaml - purpose: subagent:fix-bug match: "lib/pages.sh" turns: - tool_calls: - name: read_file input: path: lib/pages.sh - text: "The page count is an integer division, which rounds down." - purpose: judge:fix-bug match: "lib/pages.sh" turns: - json: pass: true unmet: [] feedback: "" ``` | Key | Meaning | |---|---| | `purpose` | Who is calling: `orchestrator`, `subagent:`, `judge:`, `risk`, `schedule`. A trailing `*` matches any suffix, as in `judge:*`. Required | | `match` | A substring that must appear in the system prompt or the user messages. Recordings with a `match` are tried first | | `turns` | The replies, in order. At least one | | `turns[].text` | Text of the reply | | `turns[].tool_calls` | Tool calls of the reply: `name` and `input` | | `turns[].json` | A structured reply, such as a judge's verdict | | `turns[].tokens_in`, `turns[].tokens_out` | Reported token counts. Default 100 and 20 | | `repeat_last` | Answer with the last turn once the turns are used up, instead of failing | The reply given is the turn whose index equals the number of model messages already in the conversation. Replay keeps no state, so a session resumed from a checkpoint gets the same answers. A call with no matching recording fails with `mock model: no recording for purpose ""`, and the session is not retried. The `doctor` purpose needs no recording: it is always answered with `OK`. The repository ships two sets of recordings under `testdata/recordings`: `evals/`, for the eval fixtures of every built-in skill, one file per skill (such as [fix-bug.yaml](https://github.com/xavidop/kojo/blob/main/testdata/recordings/evals/fix-bug.yaml)), and `dev/demo.yaml`, the scripted conversations of the [local dev stack](/docs/development/local-stacks/). A tier's price still applies in replay, to the recorded token counts. ### Dev stack setup The compose dev stack ([deploy/compose/kojo.dev.yaml](https://github.com/xavidop/kojo/blob/main/deploy/compose/kojo.dev.yaml)) keeps real tiers and adds a recordings directory: ```yaml models: gateway: embedded recordings: "${KOJO_DEV_RECORDINGS:-/recordings/dev}" tiers: fast: provider: anthropic model: claude-haiku-5-5 strong: provider: anthropic model: claude-opus-5-5 budgets: per_session_usd: 5 per_day_usd: 50 ``` Because the tiers are real, `KOJO_LIVE_MODELS=1` switches the same file to the live providers. The chart's CI values use the other form, with `mock` tiers: ```yaml models: recordings: /var/lib/kojo tiers: fast: provider: mock model: mock-fast strong: provider: mock model: mock-strong ``` Both fragments go inside a complete `kojo.yaml`. ### Environment variables | Variable | Effect | |---|---| | `KOJO_LIVE_MODELS=1` | Ignore `models.recordings` and call the configured gateway. Needs the providers' keys or credentials. No effect with `mock` tiers | | `KOJO_RECORD=1` | With `KOJO_LIVE_MODELS=1` and `models.recordings` set: write every live answer as a recording | Recorded answers go to `/recorded/`, one file per session and purpose, named `_.yaml` with `:` replaced by `-`. A file is rewritten after each turn. A recorded file has a `purpose` and `turns` and no `match`: add one before you keep it. The recordings directory is read recursively, so files left in `recorded/` are replayed on the next start without `KOJO_LIVE_MODELS=1`. `make record` does this for the evals. It runs them against the live model with [evals/kojo.record.yaml](https://github.com/xavidop/kojo/blob/main/evals/kojo.record.yaml), which is the eval config with real tiers and `models.recordings: out/recordings/evals`: ```sh ANTHROPIC_API_KEY= make record ANTHROPIC_API_KEY= make record SKILL=fix-bug ``` It needs `ANTHROPIC_API_KEY`, and it costs what the calls cost. The answers land in `out/recordings/evals/recorded/`, which nothing replays. Read them, check that no key or token is in one, then move the ones you keep into `testdata/recordings/evals/`, which is what `make eval` and CI replay. ## Checking the setup Validate the file, then check that every tier answers: ```sh kojo config validate -f kojo.yaml kojo doctor -f kojo.yaml ``` `kojo config validate` checks the structure: required tiers, provider names, the gateway URL, the provider settings (a project ID, a location, a region, https endpoints), non-negative budgets. It does not contact a provider. `kojo doctor`, with the embedded gateway: - checks each provider that a tier, a fallback or the embedder uses, as `model provider `: its credentials resolve, and the first model of it in tier order answers one prompt (the embedder, for a provider only the embedder uses). The detail says where the credentials came from, such as `AWS credentials from WebIdentityCredentials, region us-east-1`, never what they are. A provider that `kojo.yaml` configures and nothing uses gets the credential check only, and a failure there is a warning; - sends one prompt to each tier, with its fallbacks, as `model tier `. Each check has a timeout of 60 seconds. Doctor also reports the budgets and any tier without a price. See the [CLI reference](/docs/cli/). --- > Source: https://xavidop.github.io/kojo/docs/sandboxes # Sandboxes Every command a session runs (the repository's code, the code a model wrote, the checks of a skill) runs in a sandbox, never in the kōjō process. This page is for the person who deploys kōjō: it covers what every driver must do, the kinds of drivers and how to choose one, the settings they share, and what a sandbox image must contain. Each driver, and the egress proxy kojo-proxy, has a page of its own, listed [at the end of this page](/docs/sandboxes/#driver-pages).
A sealed glass booth with a robot arm working on a parcel inside; one pipe leaves its roof through an orange valve to a wall of sockets. A sealed glass booth with a robot arm working on a parcel inside; one pipe leaves its roof through an orange valve to a wall of sockets.
The sandbox is sealed. Its one way out is a proxy, which lets through only the allowlisted hosts and adds credentials on the way.
## The driver contract A driver is the adapter between kōjō and one sandbox backend. The contract is in [internal/sandbox/sandbox.go](https://github.com/xavidop/kojo/blob/main/internal/sandbox/sandbox.go). The core only ever talks to a sandbox through it. Every driver must do this: | Call | What the driver must do | |---|---| | `Name` | Return its key in `kojo.yaml`. | | `Create` | Start a sandbox from a spec (image, resources, workspace, egress policy, TTL) and wait until a command runs in it. Refuse a spec that asks for a Docker daemon it cannot provide, with `ErrUnavailable`. | | `Get` | Find a sandbox created earlier, also by another process or after a restart. Return `ErrNotFound` when it is gone. | | `Destroy` | Remove the sandbox and its workspace. | | `Health` | Report the isolation level, the backend version, whether sandboxes can run their own Docker daemon, and whether egress is enforced. | Every sandbox must do this: | Call | What the sandbox must do | |---|---| | `Exec` | Run a command and wait for it. Stream output, and capture stdout and stderr up to a cap. A non-zero exit code is a result, not an error. A command that times out is killed with every process it started and reported with exit code 124. | | `CopyIn` | Extract a tar stream into a directory. | | `CopyOut` | Return a file or directory as a tar stream. | | `ApplyPolicy` | Replace the sandbox's egress allowlist and credentials. The core calls it before every skill runs, which narrows the sandbox to that skill's allowlist and refreshes short-lived tokens. | Two rules hold for every driver that isolates: - A sandbox sees placeholder tokens only. Real credentials are set on requests outside the sandbox, by a proxy, and only for allowlisted hosts. - Egress is deny by default. A sandbox reaches the hosts on its allowlist and nothing else. `Health` reports one of four isolation levels: | Isolation | Meaning | Accepted outside dev mode | |---|---|---| | `microvm` | A dedicated kernel per sandbox (sbx, Kata, e2b) | yes | | `gvisor` | A user-space kernel (`runsc`) | yes | | `container` | A plain container on the host's kernel | no | | `none` | No isolation (the fake driver) | no | A session has one sandbox per image. The repository is cloned into `/workspace`. When two skills of a session name different images, the session creates a second sandbox and copies the workspace into it. The session's sandboxes are destroyed when it ends. ## Drivers A driver is one of four kinds, by where its sandboxes run: **on one machine**, the host that runs kōjō (`sbx`); **on Kubernetes**, as pods of your cluster (`k8s`); **at a sandbox service**, outside your infrastructure or cluster (`e2b`); and **for development**, as plain containers or in memory (`docker` and `fake`, which need `dev: true`). Pick the kind that matches what you run; each production kind has one driver. | Kind | Driver | Isolation | Where sandboxes run | Egress enforced by | Own Docker daemon | |---|---|---|---|---|---| | On one machine | `sbx` | `microvm` | Docker Sandboxes on the host that runs kōjō | sbx's own host proxy | yes | | On Kubernetes | `k8s` | `microvm` (Kata) or `gvisor` | Pods in a cluster, through Kubernetes Agent Sandbox | kojo-proxy plus a NetworkPolicy | with Kata only | | At a sandbox service | `e2b` | `microvm` | At an E2B-compatible service: E2B Cloud, a self-hosted E2B or CubeSandbox | kojo-proxy plus the service's firewall, set per sandbox | no | | For development | `docker` | `container` | Plain containers on a Docker daemon. Development only; needs `dev: true` | kojo-proxy plus an internal Docker network | no | | For development | `fake` | `none` | In memory; nothing runs. For tests; needs `dev: true` | nothing | no | ## Choosing a driver - **On one machine.** One machine with hardware virtualization: use `sbx`. kōjō must run on that same machine, as a host process. Its requirements and settings: [sbx driver](/docs/sandboxes/sbx/). - **On Kubernetes.** A Kubernetes cluster: use `k8s`. Use a Kata RuntimeClass when the nodes can start VMs, and gVisor when they cannot. Skills that need their own Docker daemon get one only with Kata. Its requirements and settings: [k8s driver](/docs/sandboxes/k8s/). - **At a sandbox service.** An E2B account, or a self-hosted E2B or CubeSandbox you already run: use `e2b`. kōjō then needs no virtualization and no cluster of its own, only a kojo-proxy the service's sandboxes can connect to. The service bills a sandbox while it runs. Its requirements and settings: [e2b driver](/docs/sandboxes/e2b/). - **For development.** A laptop, to work on kōjō itself or try it with code you trust: use `docker` with `dev: true`. See [Development drivers](/docs/sandboxes/docker/) and [Development](/docs/development/). Do not point `docker` or `fake` at code you do not trust. kōjō refuses to start with either unless `dev: true` is set, and `kojo doctor` fails its mode and isolation checks while it is. ## Configuring a driver The driver is boot configuration: it is set in `kojo.yaml` and changing it needs a restart. The keys below are the ones every driver reads; each driver's own keys are on its page. The full list, with every key's type, is in the [kojo.yaml reference](/docs/config-reference/), and the schema is [kojo.schema.json](/schema/kojo.schema.json). Check a file without starting anything with `kojo config validate -f kojo.yaml`. ### Settings shared by all drivers | Key | Default | Meaning | |---|---|---| | `dev` | `false` | Development mode. Allows the `docker` and `fake` drivers and a plain-container RuntimeClass on Kubernetes. | | `sandbox.driver` | none, required | `sbx`, `k8s` or `e2b`; `docker` or `fake` with `dev: true`. | | `sandbox.image` | `ghcr.io/xavidop/kojo-toolchain:`; `sandbox.e2b.template` on `e2b` | Image of a sandbox whose skill names none in its kit. On `e2b` it is a template. See [Sandbox images](/docs/sandboxes/#sandbox-images). | | `sandbox.ttl` | `4h` | How long a sandbox may live. A duration such as `90m` or `4h`. | | `sandbox.max_resources` | none | The most CPU, memory and disk any kit gets: `{cpu: "2", memory: 4Gi, disk: 20Gi}`. See [Resources, timeouts and lifetime](/docs/sandboxes/#resources-timeouts-and-lifetime). | | `sandbox.proxy.*` | see [kojo-proxy](/docs/sandboxes/proxy/) | kojo-proxy settings. Not used by `sbx` and `fake`. | ## Docker inside a sandbox A skill's kit can set `needs_docker: true` to ask for a Docker daemon of its own inside the sandbox (to build images or start services for its tests). Five built-in skills do: `reproduce-bug`, `fix-bug`, `write-tests`, `build-feature` and `flaky-test-hunt`. Whether the request is honoured depends on the driver: | Driver | `needs_docker` | |---|---| | `sbx` | Honoured. The engine runs inside the microVM. | | `k8s` with Kata | Accepted: the sandbox container runs privileged inside the pod's own VM. See the note below. | | `k8s` with gVisor | Not available. gVisor cannot run a Docker daemon. | | `k8s` with a plain-container RuntimeClass | Not available. | | `e2b` | Not available. | | `docker` | Not available. The driver never starts a privileged container. | | `fake` | Not available. | On `k8s` with Kata the driver grants the privilege and does nothing else. It replaces the image's command with a sleep loop and starts no Docker daemon, so the image must contain the Docker engine and a command in the sandbox must start it. Where it is not available, the skill is not dropped. kōjō asks the driver once whether sandboxes can run Docker. When they cannot, it creates the sandbox without Docker, and the subagent's instructions say that Docker is not available and that it must do what the task needs without building images or starting containers. `kojo doctor` warns when the driver cannot provide Docker. ## Sandbox images A skill's kit names its image. When it names none, the sandbox uses `sandbox.image`, and when that is empty, `ghcr.io/xavidop/kojo-toolchain` with the tag of the kōjō version (`latest` for development builds). The default image is built from [deploy/toolchain/Dockerfile](https://github.com/xavidop/kojo/blob/main/deploy/toolchain/Dockerfile). It is a Debian with bash, git, curl, wget, jq, ripgrep, make, a C toolchain, Python 3 with pip and venv, Go and Node.js, the Docker client with its buildx and compose plugins, a non-root user `agent` with uid 1000, and a `/workspace` that user owns. It meets the requirements of every driver below. It contains no Docker engine: a skill with `needs_docker` gets the daemon from the driver, and where the driver gives none the subagent is told to work without Docker. The release workflow builds it for linux/amd64 and linux/arm64. To build and smoke-test it locally as `ghcr.io/xavidop/kojo-toolchain:dev`: ```sh make toolchain ``` A repository with other needs names its own image in its kit. The other Dockerfiles in the repository are not sandbox images: [Dockerfile](https://github.com/xavidop/kojo/blob/main/Dockerfile) builds the `kojo` image (distroless, no shell), and [test/kind/node/Dockerfile](https://github.com/xavidop/kojo/blob/main/test/kind/node/Dockerfile) builds the kind node with gVisor. What an image must contain: | Needed by | Requirement | |---|---| | The core, on every driver | `sh`, `git`, `find`, `printf`, `tar` | | `sbx` | sbx's base image contract: `/bin/sh`, `/bin/bash`, `tar`, `git`, CA certificates, and a non-root user `agent` with uid 1000 | | `k8s` | `sh`, `env`, `tar`, `tr`, `grep`, `kill`, `sleep`. The image's own command is replaced by a sleep loop. | | `e2b` | A template instead of an image: see [Templates](/docs/sandboxes/e2b/#templates). `/bin/sh`, `id`, `mkdir`, `chown`, `cat`, `mv`, `rm`, `tar`, `tr`, `grep`, `kill` and CA certificates. Commands run as the template's default user. | | `docker` | `sh`, `sleep`, `true`, `id`, `chown`, `tar`, `tr`, `grep`, `sed`, `cut`, `kill` (BusyBox or coreutils). Commands run as the image's user. | | The egress probe of `kojo doctor` | `curl` or `wget`. Without either, the probe reports a warning instead of a verdict. | | `needs_docker` | A docker CLI in the image. On `k8s` with Kata also the Docker engine, which the driver does not start. | | The skill | Whatever its checks and `setup` commands call: the language toolchain, test runners, linters | The development compose stack uses `alpine/git`, which is enough for a repository that needs `sh` and `git` only. ## Resources, timeouts and lifetime A kit's `resources` use Kubernetes quantity syntax (`"4"`, `500m`, `8Gi`). | Resource | sbx | k8s | e2b | docker | |---|---|---|---|---| | `cpu` | Whole cores, rounded up | Request and limit | The template's | `--cpus` | | `memory` | Mebibytes, at least 512 | Request and limit | The template's | `--memory`, no swap on top | | `disk` | Ignored | Size of the workspace volume. `10Gi` when the kit names none, or `max_resources.disk` when that is less. | The template's | Not enforced | The built-in kits ask for up to 8 CPUs and 16Gi of memory. To fit them to smaller machines, set `sandbox.max_resources` in `kojo.yaml`: ```yaml sandbox: max_resources: cpu: "2" memory: 4Gi disk: 20Gi ``` A kit that asks for more than a quantity of `max_resources` gets that quantity instead, and the driver logs what it lowered. A kit that asks for less, or names no quantity, is unchanged: the cap never adds a request. A quantity `max_resources` leaves out is not capped. It applies to every kit, built-in or not, on `sbx`, `k8s` and `docker`; on `e2b` the template decides and a kit's resources are not sent. kōjō refuses to start when a quantity is not one. Besides `max_resources`, the `docker` driver lowers a request to the CPUs and memory the Docker daemon has, because Docker refuses a container with more CPUs than it has. On `k8s` a pod that no node has room for fails the sandbox after `sandbox.k8s.unschedulable_timeout`; see [Scheduling](/docs/sandboxes/k8s/#scheduling). Timeouts and caps: | What | Value | |---|---| | A command with no timeout of its own | 10 minutes | | The `run_command` tool | `timeout_seconds`, default 600, at most 3600 | | A goal check | The check's `timeout`, default 10 minutes | | A kit `setup` command, the clone | 10 minutes each | | Captured output of a command | 64 KiB each for stdout and stderr by default. Output beyond the cap is dropped from the middle. | | Sandbox creation | 15 minutes on `sbx`; 5 minutes on `k8s` and `docker`, image pull included; 3 minutes on `e2b` | | A sandbox pod no node has room for (`k8s`) | `sandbox.k8s.unschedulable_timeout`, default 2 minutes, within the 5 minutes of its creation | | Sandbox lifetime | `sandbox.ttl`, default 4 hours | A command that times out is killed inside the sandbox, with every process it started, and reported with exit code 124. A kit's `setup` commands run once per skill in a sandbox, before the skill's first attempt, and each one is recorded as a step of the session. A session that asks "Open a pull request?" keeps its change in its sandbox while it waits, so the question closes no later than 30 minutes before the sandbox's `sandbox.ttl` runs out; without an answer the change is then published as a draft. A session that asks to merge destroys its sandboxes before it waits. See [No answer](/docs/merge-policy/#no-answer). A session destroys its sandboxes when it ends. The TTL is the safety net for a session that died without cleaning up: every 5 minutes kōjō removes the sandboxes whose TTL has passed. On Kubernetes the claim also has a shutdown time 10 minutes after the TTL, so the Agent Sandbox controller deletes it when kōjō is down. On `e2b` the TTL is the service's own timeout, so the service removes the sandbox by itself. The `sbx` driver also removes generated kits that no sandbox uses, once they are 24 hours old. ## Checking a deployment `kojo doctor` reports on the sandbox setup: | Check | Fails or warns when | |---|---| | `sandbox driver` | The backend is not usable (no `sbx` binary, no virtualization, no cluster access, missing CRDs, an E2B-compatible service that cannot be reached or refuses the API key) | | `sandbox isolation` | The isolation level is `container` or `none` | | `sandbox egress` | The driver reports that sandboxes can bypass the proxy | | `sandbox docker` | Warning: sandboxes cannot run their own Docker daemon | | `egress probe` | A test sandbox with an empty allowlist reached `example.com`, through the proxy or around it | The probe creates a real sandbox from the default image. Skip it with `kojo doctor --skip-probe`. ## Conformance suite Every driver must pass one shared test suite, [test/conformance](https://github.com/xavidop/kojo/tree/main/test/conformance). It makes "a sandbox sees placeholders only and has no way out except the allowlisted proxy" a tested property of each driver. It covers: create, exec, copy and destroy; exit codes; environment; stdin; streaming; a timeout that kills the command; the output cap; workspace persistence across a new driver instance; `ErrNotFound`; a refused `needs_docker`; egress allow and deny, through the proxy and directly; placeholder to injected credential; no secret visible inside the sandbox; TTL cleanup. ```sh make conformance make conformance DRIVER=docker make conformance DRIVER=k8s make conformance DRIVER=sbx make conformance DRIVER=e2b ``` | `DRIVER` | Needs | |---|---| | `fake` (default) | Nothing. It also runs the `e2b` driver against an E2B-compatible service inside the test process, which runs a sandbox's commands on the test machine. | | `docker` | A Docker daemon | | `k8s` | The kind cluster of `make dev-kind`, described in [test/kind/README.md](https://github.com/xavidop/kojo/blob/main/test/kind/README.md). `KOJO_K8S_RUNTIME_CLASS=runc` runs it on plain containers instead of gVisor. | | `sbx` | The sbx CLI, signed in, on a host with hardware virtualization | | `e2b` | An E2B-compatible service: `E2B_API_KEY`, and `E2B_DOMAIN`, `E2B_API_URL` or `E2B_SANDBOX_URL` for one that is not E2B Cloud. `KOJO_E2B_TEMPLATE` names the template (default `base`); it needs `curl` for the egress cases. `KOJO_E2B_PROXY_HOST` is the address under which the service's sandboxes reach the machine running the tests; without it the egress and credential cases are skipped. | A case a setup cannot run is skipped with a reason that names the missing capability, and the script fails when a driver's whole test was skipped, so a skip never counts as a pass. On the `sbx` driver the egress and credential cases are skipped even on a real sbx install: the suite's throwaway upstream is not reachable through sbx's host proxy. Kata is not covered on kind, because kind nodes are containers and cannot start VMs. The local stacks and the other test layers are on the [Development](/docs/development/) page. ## Driver pages | Kind | Page | What it covers | |---|---|---| | On one machine | [sbx driver](/docs/sandboxes/sbx/) | Docker Sandboxes on the host that runs kōjō: requirements, the deny-all preset, the kits kōjō generates, limits | | On Kubernetes | [k8s driver](/docs/sandboxes/k8s/) | Agent Sandbox pods isolated by Kata or gVisor: requirements, templates and claims, isolation levels, limits | | At a sandbox service | [e2b driver](/docs/sandboxes/e2b/) | E2B Cloud, a self-hosted E2B or CubeSandbox: where kojo-proxy must be, templates, limits | | For development | [Development drivers](/docs/sandboxes/docker/) | `docker`, plain containers, and `fake`, in memory; both need `dev: true` | [kojo-proxy](/docs/sandboxes/proxy/) is the egress proxy of the `k8s`, `e2b` and `docker` drivers: how a sandbox reaches the network, embedded and remote mode, egress allowlists, credential injection, private addresses, its metrics, and how to run it apart from the server. --- > Source: https://xavidop.github.io/kojo/docs/sandboxes/sbx # sbx driver The driver for sandboxes on one machine. This page is for whoever runs kōjō on a single host with hardware virtualization, as the [single VM install](/docs/deploy/compose/) does; [Sandboxes](/docs/sandboxes/#choosing-a-driver) compares it with the other kinds. The `sbx` driver runs each session in a Docker Sandboxes microVM with its own kernel and a private Docker daemon. It drives the `sbx` CLI on the host: every operation is an `sbx` command (`sbx create`, `sbx exec`, `sbx secret set`, `sbx policy ...`, `sbx rm`). What the driver assumes beyond Docker's documentation is listed in [assumptions.go](https://github.com/xavidop/kojo/blob/main/internal/sandbox/sbx/assumptions.go). ## Requirements - kōjō runs on the same host as sbx, as a host process and not in a container. Postgres can run in compose next to it. - sbx 0.48.0 or newer. - Hardware virtualization: a usable `/dev/kvm` on Linux (KVM on, the user in the `kvm` group), or Apple silicon on macOS. - The user kōjō runs as has signed in and set the deny-all network preset: ```sh sbx login sbx policy init deny-all ``` kōjō expects the `deny-all` preset. Under `balanced` or `allow-all`, every sandbox can also reach the preset's hosts, and under `allow-all` the driver reports egress as not enforced. To switch a host that already has another preset: ```sh sbx policy reset --force && sbx policy init deny-all ``` ## Configuration The `sandbox` block of `kojo.yaml`: ```yaml sandbox: driver: sbx ttl: 4h sbx: binary: sbx kits_dir: /var/lib/kojo/sbx-kits ``` | Key | Default | Meaning | |---|---|---| | `sandbox.sbx.binary` | `sbx` on `PATH` | The sbx CLI. | | `sandbox.sbx.kits_dir` | `/kojo/sbx-kits` | Where kōjō writes the kit it generates per skill and its per-sandbox state. Every kōjō process that should see the same sandboxes must share it. | ## How it works - For each sandbox, kōjō generates an sbx kit (v3 format): a descriptor with the skill's egress allowlist and one credential route per credential and host, and a Dockerfile that starts `FROM` the skill's image. The kit holds names and hosts, never a secret. - sbx keeps the image of every kit it builds (several hundred megabytes each). kōjō's reaper removes a kit and its image once no sandbox has used it for a day. `make dev-down` removes the ones of the dev stack at once. - No host directory is shared with a sandbox. The workspace lives inside the microVM. ## Egress and credentials - sbx has its own proxy on the host, outside the microVM. It enforces the allowlist and sets the credential headers. kojo-proxy is not used with this driver, so `sandbox.proxy` has no effect. - An allowlist entry without a port allows every port of its host in sbx. kojo-proxy allows only 443 and 80 for such an entry. An entry with a port, `registry.example.com:5000`, goes to sbx as written and allows that port. - Credential values are handed to `sbx secret set --sandbox` on stdin. They appear in no kit, no environment and no command line. - kōjō writes sbx's credential approvals file (`~/.config/sbx/credentials.yaml`) itself, because there is no terminal to approve a kit's credentials on. - Inside a sandbox, `localhost` is the microVM itself. A forge that runs on the same machine as kōjō under a loopback name (the dev stack's Forgejo on `localhost:3000`) is reached as `host.docker.internal`: when a policy allows `localhost` or `127.0.0.1`, with or without a port, the driver passes git configuration that rewrites such URLs, on every command. Only git is covered. A forge with a name of its own needs none of this. ## Read-only credentials Every forge's clone credential is read-only: on a host that serves git it may be set on git's fetch and nothing else, and on a host that serves only an API on reads. sbx's proxy sets a credential on every request to its host and cannot send a request on without it, so the driver adds sandbox-scoped HTTP deny rules (`sbx policy deny network --sandbox ID HOST --method … --path …`) for each host of a read-only credential, and what they match is refused. Which rules depends on what the host serves: - A host that serves only an API (`api.github.com`, `api.bitbucket.org`) gets one rule: `POST`, `PUT`, `PATCH` and `DELETE` on any path. - A host that serves git (`github.com` or a GitHub Enterprise Server host, a GitLab or Forgejo host, `bitbucket.org`) gets 38: - `HEAD`, `OPTIONS`, `PUT`, `PATCH` and `DELETE` on any path; - `GET` and `POST` under a forge's API route, at any depth: `/api/v1` (Forgejo, Gitea), `/api/v3` (GitHub Enterprise Server), `/api/v4` (GitLab), `/api/1.0` and `/api/2.0` (`bitbucket.org`), `/api/graphql`, `/api/forgejo`, `/api/packages`, and Bitbucket's `/!api`. A fetch from a GitLab subgroup path such as `/acme/api/v4/…` is refused too; - `POST` to any path whose last segment does not start with `git-u`, and to a top-level `/git-u…`; - `GET` of any path whose last two segments are not `info/refs`, and of `/info/refs` and any one-segment path. That covers the API's reads, which hand out secrets to the bot (a GitLab project's CI/CD variables and runners token, a Forgejo repository's Actions variables and webhooks), the routes that answer with a registry or runner registration token, and the forge's web pages. sbx matches the rules against the request's path after decoding percent-escapes and dropping empty and `.` segments and a trailing slash, so `/%61pi/v4/…`, `/api//v4/…` and `/post/` meet the rules for `/api/v4/…` and `/post`. It refuses a path with a `..` segment before any rule, with a `403` whose body says "Denied due to an invalid authorization request". Both were measured on sbx 0.55.0. sbx refuses a request the rules match with its own `403`, whose body starts `Blocked by local rule`; the request does not reach the forge. kojo-proxy sends such a request on without the credential; sbx does not send it at all, so on sbx a sandbox reaches a forge's git host for git's fetch only. A request that works anonymously, such as a public repository's API, pages and archives, or Git LFS's batch request (`POST …/info/lfs/objects/batch`), fails there. ```mermaid flowchart TD R["Request from the sandbox to a host with a read-only credential"] --> N["sbx decodes escapes and drops empty and . segments and a trailing slash"] N --> DOT{"A .. segment?"} DOT -- yes --> BAD["Refused by sbx: 403, invalid authorization request"] DOT -- no --> K{"What the host serves"} K -- "an API only" --> AM{"Method"} AM -- "GET, HEAD, OPTIONS" --> SET["Sent with the credential"] AM -- "POST, PUT, PATCH, DELETE" --> DENY["Refused by sbx: 403, Blocked by local rule"] K -- git --> A{"Under /api/v1, v3, v4, 1.0, 2.0, graphql, forgejo, packages, or /!api?"} A -- yes --> DENY A -- no --> M{"Method"} M -- "HEAD, OPTIONS, PUT, PATCH, DELETE" --> DENY M -- GET --> GR{"Last two segments info/refs, after another segment?"} GR -- "no: API reads, web pages, token routes" --> DENY GR -- "yes: git's ref discovery, whatever the query" --> SET M -- POST --> G{"Last segment starts with git-u, after another segment?"} G -- "no: git-receive-pack, LFS, any other POST" --> DENY G -- "yes: git's fetch, with or without .git" --> SET ``` The rules go in right after `sbx create` and before the credential's value is stored, so the credential is never set on a write. `ApplyPolicy` adds them for a host that became read-only and removes them, by rule ID, once a credential is withdrawn or no longer read-only. The driver's state file keeps the IDs and a fingerprint of the rule set they came from: when the current set differs (a newer kōjō with other rules, or a host that now serves only an API), `ApplyPolicy` adds the current rules first and removes the old ones after, so the host is never without rules. `sbx rm` removes them with the sandbox. kojo-proxy's [rule](/docs/sandboxes/proxy/#credential-injection) is exact; sbx cannot express it, because a deny always beats an allow, a path glob cannot say "not this suffix", and no rule matches a query. On a git host sbx lets some requests through with the credential that kojo-proxy sends without it: `…/info/refs` with another query (a push's ref discovery, `service=git-receive-pack`, or git's older protocol with none, which list the same refs as a fetch's; the push itself is refused), git's paths in another case, a `POST` whose last segment only starts with `git-u` (`git-upload-packs`, `git-upload-archive`), a path that sbx cleans or decodes into git's (`//`, `.`, a trailing slash, a percent-escape), an API version no forge uses (`/api/v2/…`, `/api/3.0/…`), a `POST` to `/`, and methods no forge serves. No forge writes or hands out a secret there. Each rule takes about 0.4 seconds to add, so a sandbox with a forge's clone credential (one git host, 38 rules) takes about 15 seconds longer to create, and an API-only host adds one more. ## Limits - sbx fixes a sandbox's credential routes when it is created. kōjō therefore creates the sandbox with every credential the session's skills on that image declare. `ApplyPolicy` refreshes their values and changes the allowlist, but cannot add a credential later. - The read-only rules are per host: a credential that may write, on the same host as a read-only one, is held to them too. - `*.example.com` matches one label in sbx, not any depth. A credential host cannot be a wildcard. - sbx has no disk size setting: a kit's `resources.disk` is ignored. CPU is rounded up to whole cores, and memory has a floor of 512 MiB, after `sandbox.max_resources` has lowered them. - sbx has no TTL for local sandboxes. kōjō removes expired ones itself (see [Resources, timeouts and lifetime](/docs/sandboxes/#resources-timeouts-and-lifetime)). --- > Source: https://xavidop.github.io/kojo/docs/sandboxes/k8s # k8s driver The driver for sandboxes on Kubernetes. This page is for whoever runs kōjō on a cluster, usually with the [Helm chart](/docs/deploy/helm/); the sandboxes reach the network through [kojo-proxy](/docs/sandboxes/proxy/). The `k8s` driver runs each session in a pod managed by [Kubernetes Agent Sandbox](https://github.com/kubernetes-sigs/agent-sandbox), isolated by the cluster's Kata or gVisor RuntimeClass. It was written against Agent Sandbox v1.0.12. ## Requirements - Agent Sandbox v1.0.12 installed in the cluster (its CRDs and controller). - A RuntimeClass that isolates. The chart does not install a runtime. - kojo-proxy, and a NetworkPolicy or CiliumNetworkPolicy that only lets sandbox pods reach it, on a CNI that enforces policies. The Helm chart sets all of this up except the runtime; see [Kubernetes with Helm](/docs/deploy/helm/). ## Configuration The `sandbox` block the chart writes looks like this: ```yaml sandbox: driver: k8s ttl: 4h k8s: namespace: kojo-sandboxes runtime_class: kata warm_pool_size: 2 storage_class: fast-ssd proxy: mode: remote listen: ":3128" admin_listen: ":3129" advertise_url: http://kojo-proxy.kojo.svc:3128 # A headless Service: each address it resolves to is one proxy replica. admin_url: http://kojo-proxy-admin.kojo.svc:3129 admin_discovery: dns admin_token: "${KOJO_PROXY_ADMIN_TOKEN}" ca_cert_file: /var/run/kojo/proxy-ca/tls.crt ca_key_file: /var/run/kojo/proxy-ca/tls.key ``` | Key | Default | Meaning | |---|---|---| | `sandbox.k8s.namespace` | kōjō's own namespace in a cluster, else the kubeconfig context's | Namespace sandboxes run in. The Helm chart sets `-sandboxes`: kōjō may run commands in every pod there, so it should not be kōjō's own namespace. | | `sandbox.k8s.runtime_class` | `kata` | RuntimeClass of every sandbox pod. | | `sandbox.k8s.warm_pool_size` | `0` | Pre-warmed pods per skill. Zero keeps none: every sandbox starts cold. | | `sandbox.k8s.storage_class` | the cluster's default | StorageClass of the workspace volumes. | | `sandbox.k8s.kubeconfig` | in-cluster config | Kubeconfig file, for kōjō running outside the cluster. | | `sandbox.k8s.unschedulable_timeout` | `2m` | How long a sandbox pod may stay unschedulable before the sandbox fails. See [Scheduling](/docs/sandboxes/k8s/#scheduling). | | `sandbox.k8s.proxy_image` | none | Informational. The Helm chart deploys the proxy and writes its image here so the rendered config says what runs. The binary does not read it. | ## How it works - Per skill and kit, kōjō writes a `SandboxTemplate` named `kojo--` (image, resources, RuntimeClass, the workspace volume claim, the proxy's CA) and a `SandboxWarmPool` of the same name. The hash is that of the template, so two kits of one skill, such as two repositories' overrides of it, or a repository's override and the built-in kit, get two templates: a session's pod is always made from its own kit. Skills are runtime configuration, so the templates are created at runtime and the chart ships none. - A template that no claim uses, and that no session has asked for in the last hour, is deleted with its warm pool by the periodic cleanup that also deletes expired sandboxes. - The kit's CPU and memory are the sandbox container's requests and its limits, and its disk is the size of the workspace volume claim (`10Gi` when it names none). When `sandbox.max_resources` is set, each is lowered to it first, the default size included, and the driver logs what it lowered. - Per sandbox, kōjō creates a `SandboxClaim` named `kojo-`. The claim's name is the sandbox ID. It carries the labels `kojo.dev/session` and `kojo.dev/skill`. - The driver keeps no state outside the cluster, so any kōjō replica finds any sandbox. ## Scheduling A sandbox pod asks the scheduler for its kit's CPU and memory, the built-in kits up to 8 CPUs and 16Gi. When no node has that much free, the pod stays `Pending`: its `PodScheduled` condition is `False` with the reason `Unschedulable`, and a message such as `0/1 nodes are available: 1 Insufficient cpu.` While it waits for a sandbox, the driver reads that condition. When the pod has been unschedulable for `sandbox.k8s.unschedulable_timeout` (default 2 minutes), the driver deletes the claim, and creating the sandbox fails with an error that names the sandbox's request and quotes the scheduler: ```text k8s: sandbox kojo-5f0c… cannot be scheduled: no node took its pod in 2m0s (the sandbox of skill fix-bug requests cpu 4, memory 8Gi). The scheduler says: 0/1 nodes are available: 1 Insufficient cpu. … ``` The timeout is the time a cluster autoscaler gets to add a node; raise it when yours takes longer. Creating a sandbox has 5 minutes in all, so a value above that changes nothing. A pod that becomes schedulable within the timeout starts as usual. A sandbox that did not start is a transient failure for the session, which is [retried](/docs/concepts/#retries) twice, 30 and 60 seconds later, in case a node frees up. When it still does not fit, the session fails with this error, and the error is what kōjō answers where the request came from. A dry run (a skill test, an eval) fails at the first error. To fit the sandboxes to your nodes, lower the kits' resources (a repository's [kit.yaml](/docs/skills/kit/)) or set [`sandbox.max_resources`](/docs/sandboxes/#resources-timeouts-and-lifetime) to what a node has free after everything else it runs. The [kind stack](/docs/development/local-stacks/#the-kind-stack) sets it to 1 CPU and 2Gi, so that a sandbox fits its one 4-CPU node next to kōjō and its dependencies. ## Isolation - The isolation level comes from the RuntimeClass handler: a handler that starts with `kata` is `microvm`; `runsc` or a handler containing `gvisor` is `gvisor`; anything else is `container`. - A `container` RuntimeClass is refused, unless `dev: true` is set and the RuntimeClass carries the label `kojo.dev/insecure-dev=true`. That is how runc is used on kind. - Every sandbox container runs with `allowPrivilegeEscalation: false`, `capabilities.drop: [ALL]` and the `RuntimeDefault` seccomp profile: code in it gains nothing from a setuid binary, and an image that runs as root still holds no capability. So a kit's setup cannot install system packages; they belong in its image. The workspace's init container runs as root, because a fresh volume belongs to root and only its owner may open it to the image's user, with no capability (an owner needs none to `chmod`) and a read-only root filesystem. - A skill with `needs_docker` gets a privileged container, and only on a `microvm` RuntimeClass, where the privilege is that of the VM. Kata then passes every device of the node into the VM, unless the container runtime sets `privileged_without_host_devices = true` for the Kata runtime handler (containerd and CRI-O both have the option; Kata's own installer, kata-deploy, sets it). kōjō cannot read the node's runtime configuration, so check it before you run such skills: a repository can declare `needs_docker` in its own skills' kits. That container gets only `privileged: true`: the Docker daemon needs every capability (`SYS_ADMIN` for its mounts and cgroups, `NET_ADMIN` for its bridge and iptables rules), the devices and no seccomp filter, and Kubernetes refuses `allowPrivilegeEscalation: false` on a privileged container. ### The sandbox namespace kōjō may run commands in every pod of the sandbox namespace and write ConfigMaps there, so the [Helm chart](/docs/deploy/helm/#the-sandbox-namespace) gives sandboxes a namespace of their own, `-sandboxes`, and grants kōjō nothing in the release namespace. There: - Pod Security enforces `baseline` with gVisor and `privileged` on Kata, where a kit that needs Docker runs a privileged container in the pod's VM. `restricted` needs `runAsNonRoot`, which the workspace's init container and most kit images, running as root, do not meet. - A LimitRange gives a container that names no resources default requests and limits: the init container, and a kit without `resources`. - A ValidatingAdmissionPolicy (Kubernetes 1.30 and later) refuses pods, SandboxTemplates and Sandboxes that use the node's network, process or IPC namespace, mount a hostPath, run a privileged container (except on Kata), use another RuntimeClass or ServiceAccount, or mount a ServiceAccount token. Pod Security does not look at SandboxTemplates; the policy does, so the Role that lets kōjō write templates is no way onto the node. The conformance suite (`make conformance DRIVER=k8s`) installs the chart's policy for its namespace, so every case shows the driver's templates and pods pass it, and checks what it refuses. ## Egress and credentials - No real credential is written to the cluster. The pod spec, the claim and the ConfigMap `kojo-proxy-ca` hold the proxy's CA certificate and placeholders. - Sandbox pods carry the label `kojo.dev/sandbox=true`, which the chart's network policies select. Their service account token is not mounted. - A sandbox is given the proxy by address: kōjō resolves the host of `advertise_url` (again after 30 seconds) and puts the address it got into `HTTP_PROXY` and `HTTPS_PROXY`. So a sandbox needs no DNS, and the chart allows it none, because a resolver that forwards any name lets code in the sandbox send data out as the names it looks up. When kōjō cannot resolve the name, which is when it runs outside the cluster, the sandbox gets the name and needs DNS (`networkPolicy.sandboxEgress.dns.enabled`); kōjō logs a warning. ## Limits - The proxy variables direct traffic; they do not force it. The network policy does. `Health` reports egress as enforced only when a NetworkPolicy or CiliumNetworkPolicy labelled `app.kubernetes.io/component=sandbox-egress` in the sandbox namespace selects the sandbox pods. It does not judge the policy's rules. - Proxy settings are set per command, not in the pod spec, so that warm-pool pods work unchanged. A daemon the image starts by itself does not get them. - The CA bundle a sandbox trusts is the system roots of the machine kōjō runs on plus the proxy CA, not the roots of the sandbox image. - With `warm_pool_size` above zero, every kit in use keeps that many warm pods, until its template has been unused for an hour. - With `sandbox.proxy.mode: embedded` the k8s driver needs `sandbox.proxy.advertise_url`, because pods cannot use the address kōjō listens on. --- > Source: https://xavidop.github.io/kojo/docs/sandboxes/e2b # e2b driver The driver for sandboxes at a sandbox service, outside your infrastructure or cluster. This page is for whoever runs kōjō against such a service, from one machine or from the [Helm chart](/docs/deploy/helm/); the sandboxes reach the network through [kojo-proxy](/docs/sandboxes/proxy/). The `e2b` driver runs each sandbox at an E2B-compatible service: [E2B](https://e2b.dev) Cloud, a self-hosted E2B, or [CubeSandbox](https://github.com/TencentCloud/CubeSandbox), which serves the same API. A sandbox is a microVM the service starts from a template. kōjō uses two APIs: the service's control API, with your API key, to create, find and remove sandboxes, and the daemon inside each sandbox (`envd`), with a token the service issues per sandbox, to run commands. ## Requirements - An API key of the service. - A template with what kōjō and your skills need. See [Templates](/docs/sandboxes/e2b/#templates). - kojo-proxy at an address the service's sandboxes can connect to. See [Where the proxy must be](/docs/sandboxes/e2b/#where-the-proxy-must-be). - A service that restricts the outbound network of each sandbox (`allowOut` and `denyOut` in its API). E2B and CubeSandbox do. - From the machine kōjō runs on, HTTPS to the control API and to the sandboxes' own host names. ## Configuration ```yaml sandbox: driver: e2b ttl: 1h e2b: api_key: "${E2B_API_KEY}" template: kojo-toolchain proxy: listen: ":3128" advertise_url: http://203.0.113.7:3128 ``` A self-hosted service names its domain. One whose sandbox proxy has no wildcard domain, such as a CubeSandbox reached by address, also names that proxy: ```yaml sandbox: driver: e2b e2b: api_key: "${E2B_API_KEY}" domain: sandboxes.example.org sandbox_url: http://10.20.0.5:8080 template: kojo-toolchain proxy: advertise_url: http://10.20.0.9:3128 ``` | Key | Default | Meaning | |---|---|---| | `sandbox.e2b.api_key` | none, required | The service's API key. Use a `${VARIABLE}`. | | `sandbox.e2b.template` | none, required unless `sandbox.image` is set | The template of a sandbox whose skill names no image. `sandbox.image`, when set, is used instead. | | `sandbox.e2b.domain` | `e2b.app` | The service's domain. The daemon of the sandbox with the ID `abc` is reached at `https://49983-abc.e2b.app`. | | `sandbox.e2b.api_url` | `https://api.` followed by the domain | The control API. | | `sandbox.e2b.sandbox_url` | none | One fixed URL for every sandbox, for a service whose sandbox proxy routes by the `E2b-Sandbox-Id` header instead of by host name. | | `sandbox.proxy.advertise_url` | none, required with the embedded proxy | The address under which sandboxes reach kojo-proxy. | ## How it works ```mermaid sequenceDiagram participant K as kōjō participant A as Service API participant S as Sandbox participant P as kojo-proxy participant H as Allowlisted host K->>A: create from the template, all egress denied except the proxy's address A-->>K: sandbox ID and its envd token K->>A: read the sandbox back Note over K: The sandbox is used only when the service reports the restriction K->>S: envd, as root, install the proxy CA and create /workspace K->>P: policy with the allowlist and the credentials K->>S: envd, run a command with the proxy URL and the placeholders S->>P: request, as sandbox ID and token P->>H: the request, with the credential header set K->>A: kill, when the session ends ``` - A kit's `image` is a template name or ID on this driver. CPU, memory and disk are the template's: a kit's `resources` are not sent. - The workspace is the directory `/workspace` in the sandbox's own filesystem. The driver creates it and gives it to the template's default user, who runs every command. It lives as long as the sandbox. - `sandbox.ttl` is the service's timeout: the service kills the sandbox when it ends, whether kōjō is running or not. A TTL longer than your plan allows is refused by the service when a sandbox is created, and the error names `sandbox.ttl`. On E2B Cloud the limit is 1 hour on the Hobby plan and 24 hours on Pro. - A command's standard input is uploaded to a file in the sandbox's `/tmp` and removed when the command has opened it. - A command that times out is killed inside the sandbox with every process it started: the driver finds them by a marker in their environment, as root. ## Egress and credentials - Every sandbox is created with all outbound traffic denied and one exception, the IPv4 address of kojo-proxy, and with its public URLs closed to requests without the sandbox's access token. The driver then reads the sandbox back from the service. Outside `dev: true` it removes a sandbox whose restriction the service does not report, and the session fails, instead of running code in it. - A sandbox restricted this way has no name server either. The driver hands it the proxy as an address, and empties `/etc/resolv.conf` so that a program which looks a name up by itself fails at once instead of waiting. - The session ID, the skill, the end of the TTL and the sandbox's proxy token are stored as the sandbox's metadata at the service, so any kōjō process finds a sandbox again and nothing is kept on kōjō's side. No credential is ever sent to the service: the sandbox gets placeholders, and kojo-proxy holds the real values. ### Where the proxy must be The sandboxes run in the service's network, not in yours, and kojo-proxy is the only thing they may connect to. So: - `sandbox.proxy.advertise_url` must be an address the service's sandboxes can reach: for E2B Cloud a public IPv4 address, for a self-hosted service one that its sandbox hosts route to. E2B does not let a sandbox reach private, loopback or link-local addresses, whatever the allow list says. - Write it as `http://203.0.113.7:3128`, with the address as a number, when you can. A host name works too: kōjō resolves it and gives sandboxes the address, so the name must resolve, where kōjō runs, to the address the sandboxes can reach. - Open that port to the addresses the service's sandboxes come from, and to nothing else if the service publishes them. Every request to the proxy needs a sandbox's ID and its token; without them the proxy answers 407. - Keep the admin API (`:3129`, in `remote` mode) off that address. It takes credentials and is for kōjō only. On a single machine the embedded proxy listens on `sandbox.proxy.listen`; open that port in the machine's firewall and advertise the machine's public address. On Kubernetes, the Helm chart exposes the proxy port with `proxy.external.enabled` and takes the address in `proxy.advertiseURL`; see the [chart's README](https://github.com/xavidop/kojo/blob/main/charts/kojo/README.md). The load balancer sends a sandbox's requests to any of the proxy's [replicas](/docs/sandboxes/proxy/#several-replicas) that is ready, so E2B's allow list still names one address. ## Templates A template is the service's image of a sandbox. It must contain: - `/bin/sh` and the usual tools: `id`, `mkdir`, `chown`, `cat`, `mv`, `rm`, `tar`, `tr`, `grep`, `kill` (BusyBox or coreutils); - `git`, `find` and `printf`, which the core uses on every driver; - CA certificates, in one of the usual bundle files (`/etc/ssl/certs/ca-certificates.crt` on Debian, Ubuntu and Alpine). The driver appends the proxy's CA to a copy of it and points `SSL_CERT_FILE`, `GIT_SSL_CAINFO`, `CURL_CA_BUNDLE`, `REQUESTS_CA_BUNDLE` and `NODE_EXTRA_CA_CERTS` at the copy; - `curl` or `wget`, for the egress probe of `kojo doctor`; - whatever your skills run: the language toolchains, test runners and linters. The service builds a template from a Dockerfile. kōjō's own toolchain image has all of the above, so the shortest template is one line. Put it in a file named `e2b.Dockerfile`: ```dockerfile FROM ghcr.io/xavidop/kojo-toolchain:latest ``` Build it with the service's tooling, under a name of your choice. With the E2B CLI, which also sets the template's CPU and memory: ```sh e2b template create kojo-toolchain --dockerfile e2b.Dockerfile --cpu-count 4 --memory-mb 8192 ``` Then set `sandbox.e2b.template: kojo-toolchain`. A repository with other needs builds a template of its own and names it as the `image` of its kit. ## Limits - The service's allow list is by address, not by port: a sandbox can connect to every port of the proxy's address. Give kojo-proxy an address that serves nothing else. - `Health` reports egress as enforced when the service reports the restriction on a sandbox. When no sandbox is running to look at, `Health` (and so `kojo doctor`) creates one from the default template for a moment. - Sandboxes cannot run their own Docker daemon on this driver: a kit's `needs_docker` is not honoured. - When kojo-proxy's address changes, the egress rules of a running sandbox are replaced the next time a skill starts in it. - The connection from a sandbox to kojo-proxy is the HTTP proxy protocol, as with every driver: a request to an `https://` host is TLS inside it, the sandbox's proxy token is not. Between a hosted service and your proxy that connection crosses the internet. The [security page](/docs/security/#e2b) says what the token gives access to. --- > Source: https://xavidop.github.io/kojo/docs/sandboxes/docker # Development drivers The drivers for development: `docker` runs sandboxes as plain containers, and `fake` keeps them in memory for tests. This page is for whoever works on kōjō or tries it with code they trust; the local stacks that use these drivers are on [Local stacks](/docs/development/local-stacks/). ## docker The `docker` driver runs each sandbox as a plain Docker container. It is for development only: a container shares the host's kernel. It needs `dev: true`, and `kojo doctor` fails its isolation check. It keeps the rest of the security model, so a development setup behaves like a real one: credentials go to kojo-proxy and never into the container, and sandboxes join a Docker network created with `--internal` and `-o com.docker.network.bridge.inhibit_ipv4=true`: it has no route out, and the host has no address on it. ### Configuration ```yaml dev: true sandbox: driver: docker image: alpine/git:v2.54.1 docker: binary: docker ``` | Key | Default | Meaning | |---|---|---| | `sandbox.docker.binary` | `docker` on `PATH` | The docker CLI. | | `sandbox.docker.network` | empty | Docker network sandboxes join. When empty, kōjō creates the internal network `kojo-sandbox`. A network named here must exist. When it is not internal, or the host has an address on it, egress is not enforced and `Health` says so. | ### How it works Docker gives an internal network's bridge an address of the host, its gateway, unless the network is created with `-o com.docker.network.bridge.inhibit_ipv4=true`. At that address a container reaches every service of the host that listens on all interfaces, without the proxy: on Linux the machine itself, with Docker Desktop its VM. So the network kōjō creates has no gateway, and on a network named in `sandbox.docker.network` that has one, `Health` and `kojo doctor` report egress as not enforced and say how to recreate it. A `kojo-sandbox` network created by an earlier version has a gateway: remove it with `docker network rm kojo-sandbox` while no sandbox runs, and kōjō creates it again. How sandboxes reach the proxy depends on where it runs: - The proxy is attached to the sandbox network (docker compose): sandboxes use its service name. In `remote` mode its admin API must not listen on that network, since whoever has the admin token can change any sandbox's allowlist: set `sandbox.proxy.admin_listen` to a name only the server's network has. The development stack gives the proxy the alias `kojo-proxy-admin` on its default network and sets `admin_listen: "kojo-proxy-admin:3129"`, so the admin API listens on that address only. - The proxy is on the host (`kojo serve` on a laptop): the driver starts a relay container (`alpine/socat`) attached to the sandbox network and the default bridge. It forwards one TCP port to the proxy and nothing else. It carries at most 1024 connections at once, one process each, and waits for one to end before it accepts another; the container is limited to 1040 processes and 256 MiB. Containers run with `no-new-privileges`, without the `NET_RAW` capability, and with a limit of 4096 processes. A kit's `resources.cpu` and `resources.memory` become `--cpus` and `--memory`, in two steps. First `sandbox.max_resources`, when set, lowers what the kit asks for (see [Resources](/docs/sandboxes/#resources-timeouts-and-lifetime)). Then the driver lowers the result to what the Docker daemon has, which it reads once with `docker info` (`NCPU` and `MemTotal`) the first time a kit asks for CPU or memory. Docker refuses a container with more CPUs than the daemon has, so without this a kit that asks for 8 CPUs could not start on a 4-CPU machine. Each lowered value is logged with its reason. A kit that asks for less is unchanged, and one that names no CPU or memory gets no limit. ### Limits Sandboxes on the same network can connect to each other; `resources.disk` is not enforced; a sandbox with its own Docker daemon is refused, because that takes a privileged container; and the driver runs a few fixed shell snippets as root in the container (installing the CA bundle, killing a timed-out command). ## fake The `fake` driver keeps sandboxes in memory. Files copied in can be copied out, and no command runs. It records what the core asked for, so unit tests can assert it. The allowlist and credentials of a policy are recorded and not enforced. It needs `dev: true` and has no settings: ```yaml dev: true sandbox: driver: fake ``` --- > Source: https://xavidop.github.io/kojo/docs/sandboxes/proxy # kojo-proxy kojo-proxy is the egress proxy of the `k8s`, `e2b` and `docker` drivers. It is part of the `kojo` binary, in [internal/proxy](https://github.com/xavidop/kojo/tree/main/internal/proxy). The `sbx` driver uses sbx's own proxy instead, with the same allowlist and credentials. This page is for whoever deploys kōjō with one of those drivers: what the proxy lets through, how a credential reaches a forge, and how to run the proxy. ## How a sandbox reaches the network kojo-proxy is an HTTP forward proxy. A sandbox has no other route out: the Kubernetes network policy, the E2B-compatible service's firewall or the internal Docker network lets it open connections to the proxy and to nothing else. Each sandbox gets its own proxy username (the sandbox ID) and a random token. The driver sets them in the proxy URL of every command it runs: | Variable | Value | |---|---| | `HTTP_PROXY`, `HTTPS_PROXY`, `http_proxy`, `https_proxy` | `http://:@:` | | `GIT_HTTP_PROXY_AUTHMETHOD` | `basic`, so git sends the token with its first request; by default it first asks without it, which the proxy refuses and records | | `SSL_CERT_FILE`, `GIT_SSL_CAINFO`, `CURL_CA_BUNDLE`, `REQUESTS_CA_BUNDLE`, `NODE_EXTRA_CA_CERTS` | A CA bundle that includes the proxy's CA | | `KOJO_CRED_` | The placeholder of each credential, for example `KOJO_CRED_GITHUB` | The token is not a credential for anything else. It only selects that sandbox's policy on the proxy. For every request the proxy decides: | Decision | When | Answer to the sandbox | |---|---|---| | `allowed` | The host and port are on the sandbox's allowlist | The request is forwarded or tunneled | | `denied_host` | The host is not on the allowlist, or not for that port | HTTP 403 | | `unauthenticated` | No proxy credentials, wrong ones, or a sandbox whose policy is gone | HTTP 407 (403 inside an already open intercepted connection) | | `blocked_address` | The host is allowlisted but resolves to a non-public address | HTTP 403 | | `too_many_connections` | The sandbox already has `max_conns_per_sandbox` connections open through the proxy | HTTP 429 | A sandbox with no policy, or with an empty allowlist, reaches nothing. What the proxy does with an allowed request depends on the host: - A host with a credential: the proxy terminates TLS with a certificate signed by its own CA, sets the credential header and forwards the request over TLS to the real host. The sandbox trusts the CA through the bundle above. - Any other allowlisted host: `CONNECT` gets a blind tunnel. The proxy cannot read the stream and injects nothing. - Plain `http://` requests are forwarded, with the credential header set when the host has one. A replaced or deleted policy takes effect on the next request, also on connections that are already open. One sandbox cannot use up the proxy, which in embedded mode is the `kojo serve` process. Each sandbox may have at most `sandbox.proxy.max_conns_per_sandbox` (default 64) connections open through it at once: tunnels, intercepted connections and plain HTTP requests in flight. One more gets HTTP 429 until one closes; other sandboxes are not affected. A tunnel through which nothing has gone either way for `sandbox.proxy.idle_timeout` (default 5 minutes) is closed at both ends; bytes going one way, such as a long download, keep it open. A sandbox's keep-alive connection to the proxy is closed after the same time without a request, and a client that has not sent a request's headers within 30 seconds is disconnected. ## Embedded and remote mode The proxy runs in one of two modes: - `embedded`: inside the `kojo serve` process. The default for the `docker` and `e2b` drivers. With `e2b` it needs `sandbox.proxy.advertise_url`, because the sandboxes are elsewhere. - `remote`: its own process, started with `kojo proxy`. The default for the `k8s` driver, where it is its own Deployment. kōjō drives it through an admin API. | Key | Default | Meaning | |---|---|---| | `sandbox.proxy.mode` | `embedded`; `remote` for `k8s` | Where the proxy runs. | | `sandbox.proxy.listen` | `:3128` | Address sandboxes connect to. | | `sandbox.proxy.advertise_url` | derived from the listener | The proxy's address as sandboxes see it: `http://host:port`, without a path or user. | | `sandbox.proxy.admin_listen` | `:3129` | Address of the admin API in `kojo proxy`. | | `sandbox.proxy.admin_url` | none | The remote proxy's admin API, as kōjō reaches it: one replica, or with `admin_discovery: dns` a name that resolves to every replica. In `remote` mode it or `admin_urls` is required. | | `sandbox.proxy.admin_discovery` | empty | `dns`: every address the host of `admin_url` resolves to is a replica, resolved again every 5 seconds. See [Several replicas](#several-replicas). | | `sandbox.proxy.admin_urls` | none | The admin APIs of several replicas at fixed addresses, instead of `admin_url`. | | `sandbox.proxy.admin_token` | none | Bearer token of the admin API. Required in `remote` mode. | | `sandbox.proxy.sync_timeout` | `30s` | How long a new `kojo proxy` replica waits for a kōjō server to send it the policies before it reports ready anyway. | | `sandbox.proxy.ca_cert_file`, `ca_key_file` | none | The CA that signs certificates for hosts with a credential. Set both or neither. Several replicas need both, read by every replica. | | `sandbox.proxy.private_hosts` | empty | Hosts that may resolve to private addresses: a forge on a private network. See [Private addresses](/docs/sandboxes/proxy/#private-addresses). | | `sandbox.proxy.allow_private` | `false` | Let sandboxes reach every allowlisted host on private addresses. Prefer `private_hosts`. | | `sandbox.proxy.upstream_ca_file` | none | Extra root certificates (PEM) the proxy trusts when it connects to a host it injects credentials on: a forge with a private CA. | | `sandbox.proxy.max_conns_per_sandbox` | `64` | Connections one sandbox may have open through the proxy at once; one more gets HTTP 429. At least 1. | | `sandbox.proxy.idle_timeout` | `5m` | How long a tunnel may carry nothing either way, and a keep-alive connection go without a request, before the proxy closes it. At least `1s`. | When the CA files are set and missing, the proxy generates the CA (ECDSA P-256) and writes it: the certificate with mode 0644, the key with mode 0600. When neither is set, the CA lives in memory and is new on every start. The CA key never leaves the proxy process; sandboxes get the certificate only. `kojo proxy` takes no flags of its own. It reads `sandbox.proxy` of the `kojo.yaml` given with `-f` and nothing else, so its file may hold that section alone, with no database URL or other credential of kōjō's (the Helm chart gives it such a file, `-proxy-config`). It needs `admin_token`, and refuses to start unless `sandbox.proxy.mode` is `remote`: ```sh kojo proxy -f /etc/kojo/kojo.yaml ``` The admin API carries real credentials. Serve it on a network only kōjō reaches. Every route except `/healthz` and `/readyz` needs `Authorization: Bearer `. | Route | What it does | |---|---| | `PUT /v1/policies/{sandboxID}` | Create or replace a sandbox's policy | | `PUT /v1/policies/{sandboxID}?set_at=