llms-full.txt · git:20261115.9c370d5 · 2026-11-15 · sha256 15a456e8313dcb93

llms-full.txt git:20261115.9c370d5C

Immutable. This exact content never changes and is served at /api/v1/blob/15a456e8313dcb93.

# Caligrafy Quill 2.26.0: the complete documentation

> Every page of the Caligrafy Quill wiki (https://github.com/caligrafy/caligrafy-quill/wiki) in one file, for coding
> agents. The short index is llms.txt; exact signatures are in claude-plugin/skills/caligrafy/reference/api-reference.md
> and verified pitfalls in claude-plugin/skills/caligrafy/reference/gotchas.md. Generated by qa/build-llms-full.php.


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Home -->

# Caligrafy - Describe it. Approve it. Ship it.

**Your idea turned into a complete app.** Describe it to [Claude Code](https://claude.com/claude-code), approve the
plan, and Caligrafy ships it: the database, sign-in, web pages, a phone and tablet app, a REST API and tools for AI
agents, online at `https://<name>.caligrafy.com`, with the code in your own GitHub repository.

**Why developers choose it.** A feature is written once, as a capability, and served to pages, Vue apps, REST, AI agents over MCP
and Snap Cards, with the same rules and audit log everywhere. The same app takes 471 lines in Caligrafy against 708 in Laravel
and 1,076 in Symfony, 7 of 8 security defaults need no code, and a new project installs 16.6 MB. See
[why Caligrafy](https://github.com/caligrafy/caligrafy-quill/wiki/Why-Caligrafy): the benefits, the measurements, and what it is not yet.
## Get started quickly

With Claude Code, three steps take your idea to a complete app online:

| | You | Claude and Caligrafy |
| --- | --- | --- |
| **1. Describe it** | your idea, in a sentence: `/caligrafy-quill:idea A reading list where I rate the books I read` | turn it into a plan: a name, the tables, every feature, who may do what, the pages |
| **2. Approve it** | read the plan, change it, say OK | build every feature once, then check it from a page, REST and an AI agent |
| **3. Ship it** | approve the sign-ins in your browser | create your GitHub repository, deploy it, check it online |

```bash
git clone https://github.com/caligrafy/caligrafy-quill.git myapp
cd myapp
claude
```
```
/caligrafy-quill:idea A reading list: I add books I want to read, mark them as read, and rate them from 1 to 5.
```
You say OK once, at the plan; after that you only approve sign-ins on GitHub's and Caligrafy Cloud's own pages,
which Claude opens for you. It never asks for a password or a key, and asks before spending credits. See
[Quickstart with Claude](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart-with-Claude).

**Start from a proven prompt.** The [marketplace of caligrafy.com](https://caligrafy.com/marketplace) offers apps that
already shipped, three ways: the prompt that recreates one with Caligrafy, its code, or the app managed for you. And
once yours is online, `/caligrafy-quill:marketplace` offers it there: you earn 25% of every sale. No time to build it?
[Submit your idea](https://caligrafy.com/ideas/new) and Caligrafy builds it for you.
## A complete app: build once, experience everywhere

What makes the app complete is how Caligrafy builds it. A feature (add a task, list the books, place an order) is
written once, as a **capability**: its inputs, its rules, who may use it, and what it does. Caligrafy then serves
that same capability to every way people and machines reach your application:

| Experience | How it uses the capability |
| --- | --- |
| **Web pages** | a page calls it and shows the result |
| **Vue apps** on desktop, tablet and phone | a generated JavaScript function: `await createTask({ title })` |
| **REST API** for other applications | `POST /api/tasks` |
| **AI agents** such as Claude or Cursor | an MCP tool: `create_task` |
| **Snap Cards and the assistant** | a card a person uses, and an assistant that answers with it: `Route::snap();` ([more](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant)) |

The same validation messages, the same permissions and the same audit log, whichever way it is called. You never
write a feature twice, and the experiences never drift apart.
## By hand: the same three steps

Everything Claude does is plain Caligrafy you can write yourself, with the same files Claude writes:

| Step | What you do | With |
| --- | --- | --- |
| **1. Describe it** | a running project, your tables, and each feature written once with its rules | `.bin/caligrafer quickstart`, `create_db.sql` and a model, a capability (`php caligrafer.php service`) |
| **2. Approve it** | every experience and every permission, checked | `Route::page`, `Route::form`, `Route::auth`, `Route::capabilities`, `Route::mcp`, `scope` and `level`, tests, the reviewer, `php caligrafer.php doctor` |
| **3. Ship it** | your application at a public address | the production `Dockerfile`, `php caligrafer.php cloud deploy` |

The [course](https://github.com/caligrafy/caligrafy-quill-course) teaches both ways: with Claude, and by hand, every
file typed by you.
## Quickstart by hand: 5 minutes

You need [Git](https://git-scm.com/) and [Docker Desktop](https://www.docker.com/products/docker-desktop/)
(running). PHP, MySQL and Composer run in Docker.

```bash
git clone https://github.com/caligrafy/caligrafy-quill.git myapp
cd myapp
.bin/caligrafer quickstart --docker --example
```
`quickstart` installs the libraries, starts the server, creates the database and the framework tables, and adds a
**Tasks** example (the first start builds the PHP image: a few minutes). When it asks to delete the `.git` folder,
answer `y`: your project starts its own history. To use your own Apache and MySQL (MAMP, XAMPP, LAMP) instead, see
[Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart#composer).

**1. Use it on the web.** Open **http://localhost:8080/tasks**, add a task, tick it, rename it.

**2. Use it from another application.** The same tasks, over REST:
```bash
curl -H "Accept: application/json" http://localhost:8080/api/tasks
```

**3. Use it from an AI agent.** Create a token and give it to Claude Code (or Cursor, below):
```bash
docker compose exec dev-box php caligrafer.php token create "my agent" --scopes "*"
claude mcp add --transport http myapp http://localhost:8080/mcp --header "Authorization: Bearer <the token>"
```
Ask Claude "add a task to buy milk": it calls `create_task`, and the task appears on the web page.
In Cursor, add to `.cursor/mcp.json`:
```json
{ "mcpServers": { "myapp": { "url": "http://localhost:8080/mcp", "headers": { "Authorization": "Bearer <the token>" } } } }
```

**4. Ship it.** Push the project to a GitHub repository (`git init`, commit, push), then:
```bash
docker compose exec dev-box php caligrafer.php cloud login                 # open the address it prints, approve the code
docker compose exec dev-box php caligrafer.php cloud create myapp --repo https://github.com/<you>/myapp
docker compose exec dev-box php caligrafer.php cloud deploy myapp          # https://myapp.caligrafy.com
```
`cloud login` opens [deploy.caligrafy.com](https://deploy.caligrafy.com), where you sign in (or sign up) and approve.
Every new app is free for its first 30 minutes online. The Tasks example is open to everyone, online too: see
[Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online) before you share the address.
## Your first capability

A feature, by hand, is a table, a model, a capability and its routes. The list of a book catalog:

**`application/services/Bookshelf/ListBooks.php`** (created by
`docker compose exec dev-box php caligrafer.php service Bookshelf/ListBooks --scope books:read`)
```php
#[Capability(name: 'list_books', description: 'Lists the books, 20 per page, each with its author.', scope: 'books:read', readOnly: true)]
class ListBooks extends Service
{
    public $rules = array('author_id' => 'integer', 'page' => 'integer');

    public function handle(array $input, Context $context)
    {
        $query = Book::with('author')->orderBy('title');
        if (!empty($input['author_id'])) {
            $query->where('author_id', $input['author_id']);
        }
        return $query->paginate(20, $input['page'] ?? 1);
    }
}
```
**`application/config/routing/web.php`**
```php
Route::page('/books', 'Bookshelf/books', ['data' => ['books' => 'list_books']]);   // a web page
Route::capabilities();                                                               // REST: POST /capabilities/list_books
Route::mcp();                                                                        // AI agents: the list_books tool
```
The same capability is also a function of the generated JavaScript client (`php caligrafer.php client`). The tutorial
[Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability) builds a complete
feature step by step: the table, the model, the page, a form and sign-in.
## What comes in the box

+ **Every experience:** server-rendered pages (Pug), Vue apps and a Vite single page application, installable mobile
  web apps, REST, and an MCP server for AI agents.
+ **One rule:** only capabilities touch your data. Pages get their data from capabilities in one line
  (`Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book']])`), so a page, the API and an agent
  never follow different rules. Forms, sign-in, webhooks, downloads and anything else a browser asks are one line each too
  ([declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes): `Route::form`,
  `Route::auth`, `Route::webhook`, `Route::download`, `Route::action`): an application needs no controller.
+ **One look, or yours:** Caligrafy's look on every page: a light top bar with the Caligrafy mark, title bands, forms,
  rows and tiles, Caligrafy black for the main action, full-screen camera apps, the same on every device. Or pick one of 85 [design styles](https://github.com/caligrafy/caligrafy-quill/wiki/Design-Styles)
  (`DESIGN_STYLE` in `.env`, or your own `DESIGN.md`) and let `/caligrafy-quill:design` restyle every page.
+ **Secure by design:** sign-in, passkeys and face login for people; scoped, revocable tokens for programs and
  agents; CSRF protection; an audit log of every change; server files never served.
+ **What large apps need:** [queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries) with filters, paging,
  related rows in one query and transactions, [migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations), [background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs), [a cache](https://github.com/caligrafy/caligrafy-quill/wiki/Caching),
  [tests for your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App), [dependency injection](https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection), scheduled jobs and notifications.
+ **Fast:** in the same benchmark, Caligrafy 2.19 beats Symfony and Laravel on all 16 measures (requests per second,
  median and slowest response, memory, for plain text, JSON, a database query and an HTML page): an HTML page at
  2,887 requests per second, against 1,789 for Symfony and 324 for Laravel
  ([release notes](https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.19.0)).
+ **Batteries included:** card, ACH and crypto payments, OpenAI and open-model AI (Llama on Groq, OpenRouter,
  Ollama...), chatbots, face detection and machine learning in the browser, search and social metadata.
+ **Made for AI-assisted development:** a [Claude Code plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin)
  that knows the framework, builds features the Caligrafy way or a whole application from your idea, and puts it
  online, and `AGENTS.md` for other coding agents.
+ **Online in a few commands:** a production `Dockerfile` in every project, the database prepared at every start,
  and [Caligrafy Cloud](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online#cloud):
  `php caligrafer.php cloud deploy` puts it at `https://<name>.caligrafy.com`, every new app free for its first 30
  minutes, and `/caligrafy-quill:ship` does it all for you, from the GitHub repository to the check online.
+ **Sell what you built:** offer an app online on the [marketplace of caligrafy.com](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online#marketplace):
  Caligrafy sells a prompt that recreates it and you earn 25% of every sale. `/caligrafy-quill:marketplace` reads
  your code, screenshots its key features and submits the listing (`php caligrafer.php cloud submit`).
+ **Tools:** `php caligrafer.php doctor` checks your setup and services, `call` tries a capability in one line,
  `migrate` changes the database, `test` runs your tests, `queue work` runs background jobs,
  `update` moves a project to the latest release in one command (keeping what you changed), `upgrade` updates its
  `application/` templates and tells you what to check, `version` tells you which release you run.
## Where to go next

| You want to | Read |
| --- | --- |
| Get a feel for it | [Quickstart with Claude](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart-with-Claude) or the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart), then [How Caligrafy works](https://github.com/caligrafy/caligrafy-quill/wiki/How-Caligrafy-Works) |
| Build a feature | [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability), then [Capabilities in depth](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP) |
| Build a web page | [Views and Caligrafy's look](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#pagecomponents) |
| Build a Vue app or a single page application | [Vue as a library](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.0-Setting-up-Vue.js-as-a-library), [the single page application](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.1---Setting-up-the-Vue-application) |
| Let AI agents use your application | [MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#mcp) |
| Store data | [Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models) and [Relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships) |
| Filter, page and load related rows | [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries) |
| Take a form, sign people in, receive webhooks, export a CSV | [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes) |
| Change your tables, test your app | [Migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations), [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App) |
| Work in the background, keep slow results | [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs), [The cache](https://github.com/caligrafy/caligrafy-quill/wiki/Caching), [Dependency injection](https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection) |
| Let people sign in | [Sign-in, users and tokens](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication) (`Route::auth`), [with an email](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#emailsignin) |
| See what changed | [Release notes: 2.21.0](https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.21.0), [2.20.0](https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.20.0), [2.19.0](https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.19.0) and the [changelog](https://github.com/caligrafy/caligrafy-quill/blob/master/CHANGELOG.md) |
| Take payments, add AI, face login... | the **Built-in features** of the sidebar |
| Put it online | [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online): Caligrafy Cloud or your own server |
| Sell your app | [Selling your app on the marketplace](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online#marketplace): a prompt that recreates it, 25% of every sale |
| Build with Claude | [Claude Code plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin) |
| Learn step by step, from zero | [The Caligrafy course](https://github.com/caligrafy/caligrafy-quill-course) |
| Use the command line (set up, create, tokens, check, upgrade) | [Caligrafer: every command](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer) |
| Install another way, configure, upgrade | [Installation and configuration](https://github.com/caligrafy/caligrafy-quill/wiki/1.-Getting-Started), [Security and upgrading](https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading) |
## Community and support

+ **GitHub:** [issues](https://github.com/caligrafy/caligrafy-quill/issues) for bugs and feature requests.
+ **Slack:** [join the Caligrafy community](https://join.slack.com/t/caligrafy/shared_invite/enQtNzI4MDY2OTA4MTgzLTI2NDc2NTVmMDNlMWQ5YWYxN2RjZTkwZjdiNjM5ZTg3NjQ2YWYyMzRmZDgzNWE0Nzc4YjQyODM2NDNkNjQ2OTU) to get help and share what you build.
+ **Facebook:** the [Caligrafy group](https://www.facebook.com/groups/caligrafy/).
+ **Videos:** the [Caligrafy channel](https://www.youtube.com/playlist?list=PLsJG81fLk3_VWmXl9DnEldYY9ei4jTCjA).

If Caligrafy helps you, [sponsor it on GitHub](https://github.com/sponsors/DoryAzar) or share
[caligrafy.com](https://caligrafy.com).
Caligrafy is released under the [MIT License](https://github.com/caligrafy/caligrafy-quill/blob/master/LICENSE).


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Why-Caligrafy -->

## Describe it. Approve it. Ship it.

**An open-source PHP framework where every feature is written once and served to pages, Vue apps, REST and AI
agents. Describe your app to Claude Code, approve the plan, and it is online, with the code in your own GitHub
repository.**

Caligrafy Quill is an MIT-licensed PHP MVC framework built around one idea: a feature is a **capability**, a small
PHP class that declares its inputs, its permissions and whether it reads, writes or destroys data. Pages, forms, the
REST API, the JavaScript client, MCP tools for AI agents and Snap Cards all call that same class, through the same
checks, into the same audit log. Write it yourself, or let Claude Code write it: either way it is plain Caligrafy,
documented step by step.

---

### 1. Write a feature once, serve it everywhere

A capability is one attribute and one `handle()`. Routes decide where it shows up: a Pug page, a form, a REST
endpoint, a function of the generated JS client, an MCP tool, a Snap Card. Every call takes the same path: find,
check who calls (401/403), validate (422, one message per field), run, audit.

```php
#[Capability(name: 'create_book', description: 'Adds a book...', scope: 'books:write')]
class CreateBook extends Service
{
    public $rules = array('title' => 'required|max_len,200', 'author_id' => 'required|integer|exists,authors.id');

    public function handle(array $input, Context $context)
    {
        $id = Database::table('books')->insert($input);
        return Database::table('books')->with('author')->find($id);
    }
}
```
```php
Route::form('/books', 'create_book');            // an HTML form
Route::capabilities('/capabilities');            // REST and the JS client of your Vue apps
Route::mcp('/mcp');                              // AI agents, personal access tokens only
Route::snap();                                   // every capability as a card, with an assistant
```

### 2. Less code to write, read and change

We wrote the same Bookshelf app (pages, sign-in, a REST API with scoped tokens, two MCP tools, a CSV export, a Stripe
webhook) in each framework, the way its official docs and generators teach it.

| | Lines | Files | Concepts to learn |
|---|---|---|---|
| **Caligrafy** | **471** | **24** | **25** |
| Laravel | 708 | 40 | 42 |
| Tempest | 902 | 42 | 40 |
| Symfony | 1,076 | 39 | 42 |

Adding one more field to the form, the page, the API and the MCP tool touches **4 files** in Caligrafy, 6 to 7 in the
others.

### 3. Secure before you write a line

CSRF on every form, bound queries, mass-assignment protection, password hashing, a new session id at sign-in, token
scopes and N+1 prevention are on in a new project. A write capability without a declared scope still needs a token
with the scope named after it, and an N+1 loop throws in development with the `with()` fix in the message.

**7 of the 8 items** of the benchmark's secure-by-default checklist need no code in 2.26.0 (Tempest: 6, Laravel and
Symfony: 5). The eighth, webhook signatures, is one line: `Route::webhook` refuses to register without `verify`.

### 4. Fast on modest hardware

2.26.0 is about twice as fast as 2.25 with no change to your code: the production image sizes its PHP processes to its
container, keeps database connections, preloads the framework and compiles every view before the first visitor.
Requests per second on our benchmark machine (Docker, 2 CPUs and 1 GB per app, 32 connections):

| | Plain text | JSON | Database | HTML page |
|---|---|---|---|---|
| **Caligrafy 2.26.0** | **9,995** | **10,013** | **5,621** | **7,998** |
| Next.js 16.4 | 6,101 | 5,948 | 4,077 | 1,135 |
| Nuxt 4.6 | 53,842 | 39,975 | 12,477 | 4,182 |
| Symfony 8.1 | 2,139 | 2,141 | 1,036 | 1,830 |
| Laravel 13.42 | 267 | 850 | 457 | 266 |

Nuxt is faster on plain text, JSON and database; Caligrafy is faster on HTML pages, and faster than Next.js, Symfony
and Laravel on every test. The experimental async server (`ASYNC=on`) answers a capability call at **113,700 a
second** (JSON) and **22,100** (20 database rows, 4 processes). One machine, our setup: run it on yours before you
quote it.

### 5. Small enough to forget about

A new project installs **13 packages and 16.6 MB** (2.25: 44 packages, 72 MB). Stripe, AI SDKs, web push, passkeys and
the face-detection models come in only when you use them: `php caligrafer.php add payments`.

| New project | Caligrafy | Symfony | Laravel | Nuxt | Next.js |
|---|---|---|---|---|---|
| Install | **16.6 MB** | 24.8 MB | 45 MB | 245 MB | 546 MB |

A running container uses about **35 MB**, and the first request of a new container answers in **37 to 42 ms**.

### 6. Built for AI coding agents

Every project ships a Claude Code plugin: a skill with the framework docs, an API reference generated from the source
and a numbered list of known gotchas, plus commands for the recurring jobs (`/caligrafy-quill:new-capability`,
`/caligrafy-quill:new-resource`, `/caligrafy-quill:ship`) and `/caligrafy-quill:idea`, which takes one sentence to an app
online. Other agents (Cursor, Codex, Copilot, Gemini) get `AGENTS.md`, `llms.txt`, `llms-full.txt` and a Context7
listing. And when something is off, one read-only command checks the project and every service in `.env`:

```bash
php caligrafer.php doctor
```

### 7. Ship it, to our cloud or your server

`/caligrafy-quill:ship` commits, creates your GitHub repository, pushes and deploys to
`https://<name>.caligrafy.com` on Caligrafy Cloud, with a MySQL database and your scheduled jobs; you approve the
sign-ins in your browser, and Claude never asks for a password or a key. Prefer your own server? Every project has a
production `Dockerfile` that runs 2 PHP processes per CPU (6 with an AI key), with `PHP_PROCESSES` to override.

```bash
php caligrafer.php cloud deploy
```

---

### What Caligrafy is not (yet)

Its ecosystem is young. Laravel and Symfony have years of packages, tutorials, hosting integrations and people who
already know them; Caligrafy has its wiki, a course and a community that is just starting. The benchmarks are ours,
on one computer. If you need a big hiring pool or a package for everything today, that matters. If you want to write
a feature once and have it work for people and agents alike, try it in five minutes.

---

## Start in five minutes

**With Claude Code:**
```bash
git clone https://github.com/caligrafy/caligrafy-quill.git myapp && cd myapp && claude
```
```text
/caligrafy-quill:idea A reading list: I add books I want to read, mark them as read, and rate them from 1 to 5.
```

**By hand** (Git and Docker Desktop):
```bash
git clone https://github.com/caligrafy/caligrafy-quill.git myapp && cd myapp && .bin/caligrafer quickstart --docker --example
```
Then open http://localhost:8080/tasks.

- **Docs:** https://github.com/caligrafy/caligrafy-quill/wiki
- **Course**, with Claude or by hand: https://github.com/caligrafy/caligrafy-quill-course
- **Your first capability:** https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability
- **Release notes and benchmark:** https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.26.0

MIT-licensed. Star it, break it, open an issue.


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart-with-Claude -->

**Describe it. Approve it. Ship it.** You describe an application to [Claude Code](https://claude.com/claude-code) in a sentence, approve the plan Claude proposes, and Claude builds it the Caligrafy way (every feature written once, as a capability), checks it from every side, and puts it online at `https://<name>.caligrafy.com`. You then use the same application from a web page, your phone, other programs over REST and AI agents.

It usually takes 15 to 30 minutes, most of it Claude working. The [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart) does the setup by hand, with a ready-made example, in 5 minutes.

**Start from a proven prompt.** The [marketplace of caligrafy.com](https://caligrafy.com/marketplace) sells the prompts behind apps that already shipped: give one to `/caligrafy-quill:idea` instead of your own sentence.
## <a name="need"></a>What you need

+ [Git](https://git-scm.com/) and [Docker Desktop](https://www.docker.com/products/docker-desktop/), running
+ [Claude Code](https://claude.com/claude-code)
+ A [GitHub](https://github.com/) account. An SSH key on GitHub, or the [GitHub CLI](https://cli.github.com/) signed in, saves one step; without them, Claude installs the GitHub CLI (with Homebrew) and signs it in with a code you approve in your browser
+ An account on [Caligrafy Cloud](https://deploy.caligrafy.com/signup), or create it when Claude opens the page. Every new app is free for its first 30 minutes online
## <a name="start"></a>Start

```bash
git clone https://github.com/caligrafy/caligrafy-quill.git myapp
cd myapp
claude
```
Trust the folder when Claude Code asks: that turns on the Caligrafy plugin that ships in the project (`.claude/settings.json`). Then give it your idea:

```text
/caligrafy-quill:idea A reading list: I add books I want to read with their author, mark them as read, and rate them from 1 to 5.
```
## <a name="steps"></a>Describe it. Approve it. Ship it.

You approve **once**, at the plan. Your OK covers the rest: setting the project up (the framework's `.git` makes way for your app's own history), building it, creating a private GitHub repository and putting it online. After that Claude does not ask you to run a command or copy a key: it opens your browser when only you can approve something, and asks before spending credits.

| | What Claude does | What you do |
| --- | --- | --- |
| **1. Describe it** | | |
| The plan | turns the idea into a name, the tables, the capabilities (`list_`, `get_`, `create_`, `update_`, `delete_` per table, plus the actions the idea needs), who may do what (by default anyone reads and people who signed up change), the pages and some sample data; says what your OK lets it do | your idea, in a sentence |
| **2. Approve it** | | |
| Your OK | | read the plan, change it, say OK. Say "stop before putting it online" to review it locally first |
| Start | checks Docker and the ports, then `.bin/caligrafer quickstart`: the Docker server, the database, the framework tables, the `/capabilities` and `/mcp` routes | nothing |
| Build once | for each table a `create_db.sql` and a model; each feature as a capability (`php caligrafer.php service ...`); sign-in with `Route::auth`; the pages with `Route::page` and `Route::form`; the REST routes; the JavaScript client; a page where signed-in people create a token for their AI agents; tests | nothing |
| Check | `capabilities`, `call` on every capability, REST with and without sign-in, the page at desktop and phone width, MCP `tools/list` and `tools/call`, `test`, `doctor`, a review by the `caligrafy-reviewer` agent | nothing |
| Everywhere, locally | shows you the page at `http://localhost:8080`, a `curl` line and the line that connects an agent | try it if you like |
| **3. Ship it** (the `ship` skill) | | |
| GitHub | commits, creates the private repository and pushes: with your SSH key when GitHub knows it, else over HTTPS with the GitHub CLI, else after a browser approval | only if needed: enter the code GitHub shows in the page Claude opens |
| Online | signs in to Caligrafy Cloud (`cloud login`), creates the app, adds its read-only deploy key to the repository, deploys and checks the address | approve the code on the Caligrafy Cloud page Claude opens (sign up and confirm your email the first time) |

Claude never asks you for a password, a token or a key, and never prints one: approvals happen on GitHub's and Caligrafy Cloud's own pages. `/caligrafy-quill:ship <name>` puts any Caligrafy project online the same way, and puts it online again after a change.

### Check

Before you say OK to the plan:
+ the name is the one you want: it becomes `https://<name>.caligrafy.com` and the GitHub repository;
+ each table and capability is one you need, and nothing that changes data is open to everyone unless you want that.

Before you call it done:
+ the address Claude reports opens, you can sign up and sign in, and the main page adds and changes your data;
+ the `curl` line answers with your data;
+ `doctor` and the tests passed in Claude's report.
## <a name="result"></a>What you get

| Experience | Where |
| --- | --- |
| **Web page** | `https://<name>.caligrafy.com/`: sign up, then add and change your data |
| **Phone and tablet** | the same address, *Add to Home Screen*: it opens like an app |
| **REST API** for other programs | `curl -H "Accept: application/json" https://<name>.caligrafy.com/api/<things>` |
| **AI agents** (Claude, Cursor...) | sign in, create a token on the page, then paste the `claude mcp add ...` line it shows |
| **The code** | your GitHub repository: a Caligrafy project you can read, change and keep building, by hand or with Claude |

Every experience calls the same capabilities: the same rules, the same permissions, the same error messages.
## By hand

Every step Claude takes is a step you can take yourself: the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart) sets the project up, [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability) builds a feature with its page, REST API, agent tools, sign-in and test, and [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online) ships it. The [course](https://github.com/caligrafy/caligrafy-quill-course/wiki) builds a whole application step by step.
## <a name="next"></a>Next

+ **Change it:** ask Claude for a new feature (`/caligrafy-quill:new-capability`), or edit the code yourself. A change to a table that already has data goes in a [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations), which the deploy runs. Then `/caligrafy-quill:ship <name>`.
+ **Keep it online:** `php caligrafer.php cloud status <name>` shows the time left; `php caligrafer.php cloud extend <name> week` (2 credits) keeps it online a week. See [Caligrafy Cloud](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online#cloud).
+ **Your own server instead:** `/caligrafy-quill:deploy <name> --own-server` prepares it for Coolify or Docker ([your own server](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online#ownserver)).
+ **Learn what Claude did:** [How Caligrafy works](https://github.com/caligrafy/caligrafy-quill/wiki/How-Caligrafy-Works) in 5 minutes. Every skill is on the [Claude Code plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin) page.
## <a name="trouble"></a>Troubleshooting

| You see | Do this |
| --- | --- |
| `/caligrafy-quill:idea` is not a command | in `myapp`, run `php caligrafer.php plugin` (with PHP on your computer) or `.bin/caligrafer quickstart` (with Docker): it registers the project's plugin with Claude Code. Then restart `claude` there |
| Docker is not running | start Docker Desktop, then tell Claude to go on |
| A port is already in use (8080, 8077, 3306) | Claude gives this project other ports with a `docker-compose.override.yml` and uses them in every address |
| Your app's sign-up refuses an email address | by default usernames are letters and digits, for example `sam42` (Caligrafy Cloud's own accounts use your email). To sign in with an email, say so in the idea, or ask Claude: *"people sign in with their email, kept in the username column"* ([Signing in with an email](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#emailsignin)) |
| The name is taken on Caligrafy Cloud or GitHub | Claude proposes another name |
| The browser page did not open | Claude prints its address: open it, approve the code, and Claude goes on |
| Caligrafy Cloud says *Confirm your email first* | open the link of the email from Caligrafy (look in spam), then sign in on the same page; it can send the link again |
| You forgot your Caligrafy password | *Forgot your password?* on the sign-in page emails a 6-digit code, then you choose a new password |
| The free 30 minutes of the app are used | say yes when Claude asks to spend credits; to buy some, Claude opens the Stripe page (`cloud credits 5`) |
| The page works locally but its calls are refused online (`[ERROR 1004] Access Denied: the legacy API key is turned off`) | the page sends the shared API key, which Caligrafy Cloud turns off: ask Claude to call the routes with the JavaScript client or `apiHeaders()` |
## Related pages

+ [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart)
+ [Claude Code plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin)
+ [How Caligrafy works](https://github.com/caligrafy/caligrafy-quill/wiki/How-Caligrafy-Works)
+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart -->

The Quickstart creates a Caligrafy project on your computer and shows one feature, a list of tasks, used three ways: from a web page, from another program over REST, and from an AI agent such as Claude or Cursor. It takes about 5 minutes. Every other page of this wiki starts from the project it creates.
## <a name="claude"></a>With Claude

To build your own idea instead of the Tasks example, with Claude Code doing the work, follow the [Quickstart with Claude](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart-with-Claude):

```text
/caligrafy-quill:idea A reading list: I add books with their author, mark them as read and rate them from 1 to 5.
```

Claude sets the project up with the same command as step 2 below (without the example), then builds, checks and ships the app.
## By hand

### <a name="need"></a>What you need

+ [Git](https://git-scm.com/)
+ [Docker Desktop](https://www.docker.com/products/docker-desktop/), running
+ The ports `8080` (the site), `8077` (phpMyAdmin) and `3306` (MySQL) free on your computer. If one is taken, see [Troubleshooting](#trouble) first.

PHP 8.5, Apache, MySQL 8.4 and phpMyAdmin run in Docker: you do not install them. Without Docker, see [Other ways](#composer).

### <a name="start"></a>1. Get the framework

```bash
git clone https://github.com/caligrafy/caligrafy-quill.git myapp
cd myapp
```

`myapp` is the folder of your project. Choose any name.

### 2. Set the project up

```bash
.bin/caligrafer quickstart --docker --example
```

It asks first:
```text
quickstart initializes the project, which deletes the .git folder of the framework (your project starts its own history).
Continue? [y/N]
```
Answer `y`. The `.git` folder is the history of the framework; your project starts its own in [Put it online](#online).

The command installs the PHP libraries (with your Composer, or Composer in Docker), builds and starts the Docker server (the first build takes from under a minute to a few minutes), then sets the project up inside it. It ends with:
```text
Caligrafy quickstart (Docker server)
  OK    Project: application/ and .env created, keys generated
  OK    .env: the database of the Docker server (caligrafy)
  OK    Database: caligrafy ready on mysql
  OK    Framework tables: tokens, audit log, job runs, jobs, cache, migrations
  OK    Routes: /capabilities (JS client), /mcp (AI agents), /notify (notification emails)
  OK    Example: 9 file(s) added (application/services/Tasks, models/Tasks, views/Tasks, public/js/tasks.js)
  OK    Example table: tasks
  OK    Example client: public/js/capabilities.js generated

Ready. Next:
  - open http://localhost:8080/tasks: the same tasks over REST (http://localhost:8080/api/tasks) and MCP (http://localhost:8080/mcp)
  - write a capability: php caligrafer.php service Books/CreateBook --scope books:write
  - let an AI agent use it: php caligrafer.php token create "my agent" --scopes "*"
    claude mcp add --transport http myapp http://localhost:8080/mcp --header "Authorization: Bearer <token>"
  - check everything: php caligrafer.php doctor
```

| Line | What it did |
| --- | --- |
| Project | ran `php caligrafer.php initialize`: copied the templates to `application/`, created `.env` with a new `APP_KEY` and `API_KEY`, deleted `.git` |
| .env | set `DB_ACTIVATE=true`, `DB_HOST=mysql` and `DB_DATABASE=caligrafy` |
| Database, Framework tables | created the database and the tables of personal access tokens, the audit log, jobs, the cache and migrations (`php caligrafer.php platform install`) |
| Routes | added `Route::capabilities('/capabilities')`, `Route::mcp('/mcp')` and `Route::notifications()` to `application/config/routing/web.php` |
| Example | added the Tasks example (`--example`): five capabilities, a model, a page, the `tasks` table, its routes and the JavaScript client |

Leave out `--example` for an empty project. Every step can be run again: `quickstart` only does what is missing and never overwrites your files.

When Claude Code is installed on your computer, the command also registers the project's Claude Code plugin and prints `Claude Code plugin: caligrafy-quill@caligrafy-<name>, read from this folder`.

### <a name="use"></a>3. Use the feature on a web page

Open **http://localhost:8080/tasks**. Add a task, tick it done, rename it, delete it. Submit an empty task: the page shows `The Title field is required`.

### 4. Use it from another program, over REST

```bash
curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" \
     -d '{"title": "Try the quickstart"}' http://localhost:8080/api/tasks
```
```json
{"data":{"id":1,"title":"Try the quickstart","notes":"","done":0,"created_at":"2026-11-07 23:14:07","modified_at":"2026-11-07 23:14:07"}}
```
```bash
curl -H "Accept: application/json" http://localhost:8080/api/tasks
```
```json
{"data":[{"id":1,"title":"Try the quickstart","notes":"","done":0,"created_at":"2026-11-07 23:14:07","modified_at":"2026-11-07 23:14:07"}]}
```
A task without a title gets `422` and the same message as the page:
```bash
curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" -d '{}' http://localhost:8080/api/tasks
```
```json
{"error":{"code":"invalid","message":"Some of the inputs are invalid","fields":{"title":"The Title field is required"}}}
```
Always send `Accept: application/json`: without it, a `POST` is treated as a form and refused with `[ERROR 3000] Security Error - Cross Site Forgery` (403).

### 5. Use it from an AI agent

Agents sign in with a **personal access token**. Create one that may read and change tasks:
```bash
docker compose exec dev-box php caligrafer.php token create "my agent" --scopes tasks:read,tasks:write
```
```text
 Token #1 "my agent" created with tasks:read tasks:write

 cq_1_...

 It is shown only now: store it as a secret (Authorization: Bearer <token>).
```
Copy the `cq_...` value. Give it to **Claude Code**:
```bash
claude mcp add --transport http myapp http://localhost:8080/mcp --header "Authorization: Bearer cq_1_..."
```
or to **Cursor**, in `.cursor/mcp.json`:
```json
{ "mcpServers": { "myapp": { "url": "http://localhost:8080/mcp", "headers": { "Authorization": "Bearer cq_1_..." } } } }
```
Ask the agent "add a task to buy milk". It calls the `create_task` tool. The open `/tasks` page shows the new task within 3 seconds, without a reload.

To check the endpoint without an agent:
```bash
curl -H "Authorization: Bearer cq_1_..." -H "Content-Type: application/json" \
     -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' http://localhost:8080/mcp
```
The answer lists the tools this token may use: `create_task`, `delete_task`, `get_task`, `list_tasks`, `register_user`, `update_task` (`register_user` is the public sign-up of the project).

### 6. Check the project

```bash
docker compose exec dev-box php caligrafer.php doctor
```
The last line is:
```text
 15 OK, 0 WARN, 0 FAIL, 6 SKIP
```
The `SKIP` lines are the services you have not configured yet (OpenAI, Groq, Stripe, Coinbase, Watson, mail).

### Check

+ `http://localhost:8080/tasks` opens, and a task added there is listed by `curl http://localhost:8080/api/tasks`.
+ An empty title gets `The Title field is required` on the page, over REST and from the agent.
+ `doctor` ends with `0 FAIL`.
## <a name="what"></a>What you just used

The Tasks feature is written once, as five **capabilities** (one class per action) in `application/services/Tasks/`: `list_tasks`, `get_task`, `create_task`, `update_task` and `delete_task`. The page, the REST API and the agent all call them, so the rules are the same everywhere. These lines of `application/config/routing/web.php` serve them:

```php
    // BUILD ONCE: every capability, for the JS client and AI agents
    Route::capabilities('/capabilities');   // the capabilities for the JS client of the Vue apps
    Route::mcp('/mcp');                     // the capabilities as tools for AI agents (personal access tokens)
    Route::notifications();                 // the pages notification emails link to (confirm, unsubscribe)

    // TASKS EXAMPLE: one set of capabilities (application/services/Tasks) served to every channel
    Route::page('/tasks', 'Tasks/index');   // the web page (public/js/tasks.js)
    Route::capability('GET', '/api/tasks', 'list_tasks');                // REST
    Route::capability('GET', '/api/tasks/{id}', 'get_task');
    Route::capability('POST', '/api/tasks', 'create_task');
    Route::capability('PUT', '/api/tasks/{id}', 'update_task');
    Route::capability('DELETE', '/api/tasks/{id}', 'delete_task');
```

| File | What it is |
| --- | --- |
| `application/services/Tasks/*.php` | the five capabilities |
| `application/models/Tasks/Task.php`, `create_db.sql` | the model of the `tasks` table, and the script that created it |
| `application/views/Tasks/index.pug` | the page |
| `public/js/tasks.js` | the page's script: it calls the capabilities through `public/js/capabilities.js`, the generated JavaScript client |

[How Caligrafy works](https://github.com/caligrafy/caligrafy-quill/wiki/How-Caligrafy-Works) explains the idea in a few minutes. [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability) builds a feature of your own.

> **The example is open to everyone.** Its capabilities are `public: true`: anyone who reaches the site can add and delete tasks, without signing in. Before you put an application online, remove `public: true` from the capabilities that change data and turn on sign-in: [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability#secure) shows how.
## <a name="everyday"></a>Every day

| To | Run (in the project folder) |
| --- | --- |
| start the server | `.bin/caligrafer server start` (or `docker compose up -d dev-box`) |
| stop it | `.bin/caligrafer server stop` (or `docker compose stop`) |
| run a Caligrafer command | `docker compose exec dev-box php caligrafer.php <command>` ([every command](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer)) |
| look at the database | phpMyAdmin at http://localhost:8077, user `root`, password `root` |

`server start` prints:
```text
Caligrafy Server successfully started.

 Hostname: http://localhost:8080
 phpmyadmin: http://localhost:8077
 mysql: localhost:3306 (from your computer; mysql:3306 from the containers)
 mysql username: root 
 mysql password: root 
```
Stop the server with `stop`, never `docker compose down`: the MySQL container keeps its data only until it is removed.
## <a name="online"></a>Put it online

The same project runs online with [Caligrafy Cloud](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online#cloud) at `https://<name>.caligrafy.com`, built from its GitHub repository. Every new app is free for its first 30 minutes online.

1. **Your code on GitHub.** `quickstart` removed the framework's history, so start yours, then create a repository on GitHub (private works too) and push to it:
    ```bash
    git init -b main
    git add -A
    git commit -m "My app"
    git remote add origin https://github.com/<you>/myapp.git
    git push -u origin main
    ```
2. **Sign in to Caligrafy Cloud.** Create an account at [deploy.caligrafy.com](https://deploy.caligrafy.com/signup) and confirm your email. Then:
    ```bash
    docker compose exec dev-box php caligrafer.php cloud login
    ```
    It prints a code and an address: open the address, check the code and approve it. In Docker it does not open the browser for you.
3. **Create the app and deploy it:**
    ```bash
    docker compose exec dev-box php caligrafer.php cloud create myapp --repo https://github.com/<you>/myapp
    docker compose exec dev-box php caligrafer.php cloud deploy myapp
    ```
    For a private repository, `cloud create` prints a read-only deploy key (also saved in `.caligrafy/myapp-deploy-key.pub`): add it to the repository on GitHub (*Settings > Deploy keys*) before `cloud deploy`. `cloud deploy` follows the build, which takes a few minutes, and ends with the address.

Open `https://myapp.caligrafy.com/tasks`: the production image ran `php caligrafer.php deploy`, which created the tables, when it started. `/caligrafy-quill:ship` in Claude Code does all three steps for you.

> **Online, the Tasks example is open to everyone too.** That is fine for a 30-minute try; for longer, remove `public: true` first. When the free time ends the app is paused; `php caligrafer.php cloud extend myapp week` (2 credits) brings it back.
## <a name="next"></a>Next

+ **Build your own feature:** [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability) adds a Bookshelf: its table, its capabilities, a page with a form, a REST API, agent tools, sign-in and a test.
+ **Remove the example:** delete `application/services/Tasks`, `application/models/Tasks`, `application/views/Tasks` and `public/js/tasks.js`, the `TASKS EXAMPLE` lines of `application/config/routing/web.php`, then run `docker compose exec dev-box php caligrafer.php client` again.
+ **Every command:** the [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer) page.
## <a name="trouble"></a>Troubleshooting

| You see | Do this |
| --- | --- |
| `Docker is not running: start Docker Desktop, then run .bin/caligrafer quickstart again.` | Start Docker Desktop, wait until it says it is running, run the command again |
| `port is already allocated` (8080, 8077 or 3306) | Another server uses the port. Stop it, or give this project other ports with a `docker-compose.override.yml` next to `docker-compose.yaml` (below), and use those ports in every address. `quickstart` still prints `8080` |
| The PHP image build fails or stops (`Killed`) | A slow or filtered network, or too little memory for Docker: run the command again, or give Docker more memory |
| `FAIL  Database: could not reach mysql` | MySQL takes a few seconds on its first start: run `.bin/caligrafer quickstart --docker --example` again |
| `STOP  initialize deletes the .git folder of the framework` | You answered no: run the command again and answer `y` |
| The page is empty or shows an error | `docker compose exec dev-box php caligrafer.php doctor` lists what is wrong, with a fix for each line |

**Other ports.** The site, phpMyAdmin and MySQL on 8081, 8078 and 3307 (Docker Compose 2.24 or later reads `!override`):
```yaml
# docker-compose.override.yml
services:
  dev-box:
    ports: !override
      - "8081:80"
  phpmyadmin:
    ports: !override
      - "8078:80"
  mysql:
    ports: !override
      - "3307:3306"
```
## Other ways

### <a name="composer"></a><a name="nodocker"></a>With Composer, on MAMP, XAMPP or LAMP

Use this when you already run a local Apache and MySQL (MAMP, XAMPP, or Apache and MySQL on Linux) and have PHP 8.3+ and [Composer](https://getcomposer.org). Create the project **in the web folder** of that server (MAMP: the folder of its Apache settings, `htdocs` by default; XAMPP: `htdocs`; LAMP: `/var/www/html`):
```bash
composer create-project caligrafy/caligrafy-quill myapp
cd myapp
.bin/caligrafer quickstart --local --example
```
`composer create-project` downloads the latest release and its libraries, then prints where the project will be served and the next command. `quickstart --local`:

1. initializes the project (there is no `.git` to delete in a release);
2. gives the project its address (`APP_ROOT`, its path in the web folder). With MAMP it reads MAMP's own settings: its web folder, its Apache port and its MySQL port;
3. asks for the MySQL settings, with the server's defaults (MAMP: `127.0.0.1`, port `8889`, `root` / `root`; XAMPP: `127.0.0.1`, `3306`, `root` and no password; LAMP: `localhost`, `3306`, `root` and no password) and a database named after the folder;
4. creates the database, the framework tables, the routes and the example, like the Docker quickstart.

Then open the address it prints, for example `http://localhost:8888/myapp/tasks` with a default MAMP.

+ The project is elsewhere: add `--url http://localhost/<folder>` to give its address.
+ No terminal to answer the questions (a script): it skips the database. `--db-defaults` takes the server's defaults; `--no-db` skips the database on purpose.
+ The MySQL settings do not work: it sets `DB_ACTIVATE=false` again, so that the pages still open, and says what to fix in `.env`.
+ On **Windows** (XAMPP, MAMP for Windows): `php caligrafer.php quickstart --example`.
+ Without `--local` or `--docker`, `.bin/caligrafer quickstart` uses the local server when Apache (`httpd` or `apache2`) is running and PHP is installed, else Docker.

### <a name="ownmysql"></a>Your own PHP and MySQL, settings first

When you know the MySQL settings, write them before `quickstart` and nothing is asked:
```bash
git clone https://github.com/caligrafy/caligrafy-quill.git myapp
cd myapp
composer install
cp framework/settings/.env.example .env
```
In `.env`, set `DB_ACTIVATE=true`, `DB_HOST` (`127.0.0.1`, not `localhost`, to use `DB_PORT`), `DB_PORT`, `DB_DATABASE`, `DB_USERNAME` and `DB_PASSWORD`. Then:
```bash
php caligrafer.php quickstart --example --yes --url http://localhost/myapp
```
`--yes` deletes the framework's `.git` without asking; `--url` is the address your Apache serves the folder at. The output is the one of step 2, with `OK    Local server: your server, http://localhost/myapp (APP_ROOT=myapp)` and `OK    Database: <DB_DATABASE> ready on 127.0.0.1` in place of the Docker lines. Apache must allow the project's `.htaccess` (`AllowOverride All`) with `mod_rewrite` and `mod_headers`: see [Getting Started](https://github.com/caligrafy/caligrafy-quill/wiki/1.-Getting-Started#protecting-your-server-files).
## Related pages

+ [Quickstart with Claude](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart-with-Claude)
+ [How Caligrafy works](https://github.com/caligrafy/caligrafy-quill/wiki/How-Caligrafy-Works)
+ [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability)
+ [Getting Started](https://github.com/caligrafy/caligrafy-quill/wiki/1.-Getting-Started): every way to install, the configuration and the server rules
+ [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer)
+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)

<br/><br/>
>[Next: How Caligrafy works](https://github.com/caligrafy/caligrafy-quill/wiki/How-Caligrafy-Works)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/How-Caligrafy-Works -->

Caligrafy is a PHP framework built on one idea: **build once, experience everywhere**. You write each feature of your application once, as a **capability**, and every way people and programs reach the application (web pages, Vue apps, a REST API, AI agents) calls that same capability. This page explains the few ideas behind it in about 5 minutes. To try it first, follow the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart).

You can build with Claude Code, which follows these ideas for you (`/caligrafy-quill:idea`, see the [Quickstart with Claude](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart-with-Claude)), or by hand, following [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability). Both produce the same project.
## <a name="capability"></a>A capability is a feature, written once

A **capability** is one thing your application can do: list the books, add a book, lend a book. It is a small PHP class in `application/services/` that says four things:

| What | Where in the class | Example |
| --- | --- | --- |
| its name and what it does | the `#[Capability]` attribute | `name: 'create_book'`, `description: 'Adds a book...'` |
| the inputs it accepts and their rules | `$rules` | `'title' => 'required\|max_len,200'` |
| who may use it | the `#[Capability]` attribute | `scope: 'books:write'`, `level: 1`, or `public: true` |
| the work | `handle()` | save the book, return it |

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;

#[Capability(
    name: 'create_book',
    description: 'Adds a book to the Bookshelf catalog and returns it with its id and its author.',
    scope: 'books:write'
)]
class CreateBook extends Service
{
    public $rules = array(
        'title' => 'required|max_len,200',
        'published_year' => 'required|integer|min_numeric,1450|max_numeric,current_year',
        'author_id' => 'required|integer|exists,authors.id'
    );

    public function handle(array $input, Context $context)
    {
        $id = Book::insert($input);   // one INSERT, every value bound
        return Book::with('author')->find($id);
    }
}
```

A capability returns data, or refuses with a `ServiceError` (`invalid`, `unauthenticated`, `forbidden`, `not_found`, `conflict`). It does not draw a page, redirect or answer HTTP itself. That is what lets every experience use it. (A few requests only make sense in a browser, such as a sign-in between two sites: those are [web-only capabilities](#webonly).) Inside it, the [query builder](https://github.com/caligrafy/caligrafy-quill/wiki/Queries) reads the data: `Book::with('author')->where('author_id', 2)->paginate(20, $input['page'] ?? 1)`.
## <a name="experiences"></a>Experiences call the capabilities

An **experience** is a way to reach your application. Each one is shaped for its audience, and each one calls the same capabilities. One line of `application/config/routing/web.php` connects each:

| Experience | Who uses it | How it reaches `create_book` |
| --- | --- | --- |
| Web pages (Pug) | people in a browser | the page gets its data from a read-only capability (`Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book']])`), and its form posts to `Route::form('/books', 'create_book', ['success' => '/books/{id}'])` |
| Vue apps and page scripts | people on desktop, tablet and phone | `await createBook({ title, published_year, author_id })` from the generated JavaScript client (`php caligrafer.php client`, served by `Route::capabilities('/capabilities')`) |
| REST API | other programs | `POST /api/books` (`Route::capability('POST', '/api/books', 'create_book')`), or `POST /capabilities/create_book` |
| AI agents (MCP) | Claude, Cursor and other agents | the `create_book` tool (`Route::mcp('/mcp')`) |
| The command line and tests | you | `php caligrafer.php call create_book title=Kindred published_year=1979 author_id=2`, `$this->call('create_book', [...])` in a test |

The other needs of a web application are one line each, and call capabilities too ([Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes)): `Route::auth()` for sign-in, sign-out and sign-up, `Route::webhook()` for the events a payment provider posts, `Route::download()` for a CSV export or many files as one ZIP, `Route::redirect()` for an address that moved, and `Route::action()` for whatever a page or a form cannot say. Every request of the application is declared this way: there is no controller to write. Work that runs later or on a timer is a capability too, pushed as a [background job](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs) or named in a [schedule](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs).

### <a name="webonly"></a>Web-only capabilities

Most features belong on every experience. A few belong to the browser: a sign-in between two sites, a face sign-in, a page that chooses where to go, a gate, a page that creates a payment. They need the session, or they answer with a page or a redirect. Such a capability is declared `webOnly: true`, and returns a `Caligrafy\Web`:

```php
#[Capability(name: 'open_author_books', description: 'Opens the books of an author.', readOnly: true, public: true, webOnly: true)]
class OpenAuthorBooks extends Service
{
    public $rules = array('author_id' => 'required|integer');

    public function handle(array $input, Context $context)
    {
        $books = $this->capability('list_books', array('author_id' => $input['author_id']), $context);
        return $books['total'] == 1 ? Web::redirect('/books/' . $books['data'][0]['id']) : Web::view('Bookshelf/books', array('books' => $books));
    }
}
```

`Route::action('/authors/{author_id}/books', 'open_author_books');` serves it, and **nothing else reaches it**: REST, MCP, the JavaScript client, the command line, `Route::page` and `Route::form` answer "There is no capability". It keeps the rules of every capability (who may call it, its inputs, its audit log). It may also read the session, sign people in, and change data on a `GET`, which is why it stays on the web. What other experiences need stays in plain capabilities, which it calls with `$this->capability()`.
## <a name="identity"></a>Who is calling

Every call knows who makes it, in its `Context`:

+ **People** sign in (password, passkey). A capability can ask for a minimum permission level, `level: 1`, read from the `permissions` column of `users`.
+ **Programs and AI agents** use a **personal access token** (`php caligrafer.php token create "my agent" --scopes books:read,books:write`). A token reaches only the capabilities its scopes allow, can expire, and can be revoked on its own.
+ **Public** capabilities (`public: true`) need neither: use it for data anyone may read.
## <a name="call"></a>What happens on every call

Whatever the experience, every call goes through the same steps:

1. **Find** the capability (unknown: `404`).
2. **Check who calls**: signed in or a token (`401`), with the scope and the level (`403`), unless the capability is public.
3. **Check the inputs** against `$rules`, keeping only the declared inputs (`422`, with a message per field).
4. **Run** `handle()`.
5. **Record** it in the audit log: every change and every refusal (`php caligrafer.php audit`). Reads that succeed are not recorded.

So a book without an author gets `The Author Id field is required` on the web page, over REST and for an agent, and a token without `books:write` is refused everywhere.
## <a name="online"></a>From your computer to the internet

The project you build is the project you put online, unchanged:

+ a production `Dockerfile` at its root builds it (PHP, Apache, your libraries, no development tools);
+ when the container starts, `php caligrafer.php deploy` creates the framework tables, runs every new or changed `create_db.sql`, then the [migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations) that never ran, and Apache starts;
+ `php caligrafer.php cloud deploy <name>` puts it at `https://<name>.caligrafy.com` with [Caligrafy Cloud](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online#cloud), or you run the same image on [your own server](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online#ownserver).

Online, every experience calls the same capabilities with the same rules. With Claude, the whole path is three steps: **describe it** (the idea becomes a plan), **approve it** (your OK; Claude builds once and checks every experience) and **ship it** (GitHub and Caligrafy Cloud).
## <a name="where"></a>Where things live

```text
application/
├── services/      the capabilities: each feature, once (Users/: the people who sign in)
├── models/        one class per table, with the create_db.sql that creates it
├── migrations/    changes to tables that hold data: numbered SQL files, each run once (php caligrafer.php migrate)
├── views/         the web pages (Pug), on the layout default/master/site
├── controllers/   the example controllers of a new project (core/); a new request never needs one
└── config/        routing/web.php: the routes; config.php: the site's settings;
                   schedule.php (scheduled jobs) and container.php (constructor bindings) when you add them
tests/             your tests (php caligrafer.php test)
Dockerfile         the production image (php caligrafer.php deploy runs when it starts)
public/
├── js/capabilities.js       the generated JavaScript client
├── css/                     Caligrafy's look: tokens.css (design tokens), layout.css, look.css, camera.css
└── <app>/                   Vue apps and single page applications
```

**One rule keeps every experience the same: only capabilities touch models.** Pages get their data from capabilities (`Route::page` with `data`, or the JavaScript client), forms post to capabilities (`Route::form`), custom requests are capabilities too (`Route::action`), REST and AI agents call capabilities. `Route::page` also gives every view who is signed in (`$authorized`, `$user`).

Caligrafy is also a classic MVC framework (routes, controllers, models, views). Existing controllers keep working: they call capabilities with `$this->call()`, and the [Controllers](https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers) page shows how to move one. New code does not need them: start with capabilities and the declarative routes, and use `Route::action` for what a page or a form cannot say.
## Related pages

+ [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart) and [Quickstart with Claude](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart-with-Claude)
+ [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability): a complete feature, by hand
+ [Build Once: Services, Capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP): every option
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes) and [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries)
+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)

<br/><br/>
>[Next: Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability -->

In this tutorial you add a **Bookshelf** to the project of the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart): an `authors` and a `books` table, four capabilities (list the books, get one, list the authors, add a book), a page with a form, a REST API, tools for AI agents, sign-in, a test and a migration. It is the Bookshelf of the [course](https://github.com/caligrafy/caligrafy-quill-course), with the same tables and the same code. About 30 minutes. Every command runs in the project folder, with the Docker server of the Quickstart running.

A **capability** is one feature of the application, written once as a PHP class: its inputs and their rules, who may use it, and the work. Pages, REST, the JavaScript client and AI agents all call the same capability.
## With Claude

```text
/caligrafy-quill:new-resource Author name:string bio:text
/caligrafy-quill:new-resource Book title:string published_year:int summary:text author:fk
```

For each entity, the `new-resource` skill writes the table script (`application/models/Book/create_db.sql`, the parent table first, with the foreign key `author_id`), the model, the five capabilities `list_books`, `get_book`, `create_book`, `update_book` and `delete_book` in `application/services/Books/` (scopes `books:read` and `books:write`), their REST routes, the pages with `Route::page` and the forms with `Route::form`. It then offers to run the SQL (`/caligrafy-quill:db`), calls each capability and asks the `caligrafy-reviewer` agent to review the files. The skill keeps one folder per entity (`models/Book/`, `services/Books/`, `views/Books/`); the steps below keep the whole Bookshelf in `Bookshelf/` folders, as the course does: both work. For one feature at a time, `/caligrafy-quill:new-capability create_book books:write` does the same for one capability and checks that every channel answers and refuses the same way.

**Check** before you say OK:
+ `docker compose exec dev-box php caligrafer.php capabilities` lists the new capabilities with the scopes you expect (`books:read`, `books:write`) and `read` only on the reads.
+ `author_id` has the rule `exists,authors.id`: a book with an unknown author is refused with a message, not a database error.
+ No capability that changes data is `public: true`, unless you asked for it.
+ `web.php` has no controller: the forms are `Route::form` lines.
+ The page opens, and an empty form shows a message under each required field.
## By hand

In Docker, every `php caligrafer.php` command runs as `docker compose exec dev-box php caligrafer.php ...`. On your own PHP, run `php caligrafer.php ...` in the project folder.

### <a name="table"></a>1. The tables and their models

A **model** is a PHP class for one table, with one public property per column. Create the folder `application/models/Bookshelf` and three files in it.

**`application/models/Bookshelf/create_db.sql`**
```sql
/* Bookshelf: the first version of its tables, and sample books.
 * Run it with: docker compose exec dev-box php caligrafer.php sql application/models/Bookshelf/create_db.sql
 * Safe to run again: CREATE TABLE IF NOT EXISTS skips a table that exists, INSERT IGNORE a row whose id exists.
 * Never edit it once it ran on a database with data: change a table with a migration (step 9).
 */

CREATE TABLE IF NOT EXISTS authors (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    name VARCHAR(150) NOT NULL,
    bio TEXT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;

CREATE TABLE IF NOT EXISTS books (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    title VARCHAR(200) NOT NULL,
    published_year SMALLINT UNSIGNED NOT NULL,
    summary TEXT NULL,
    author_id INT UNSIGNED NOT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_books_author_id (author_id),
    CONSTRAINT fk_books_author_id FOREIGN KEY (author_id) REFERENCES authors (id)
        ON UPDATE CASCADE ON DELETE RESTRICT
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;

-- Sample data, with fixed ids so that book 3 is Kindred everywhere
INSERT IGNORE INTO authors (id, name, bio) VALUES
    (1, 'Ursula K. Le Guin', 'American author of science fiction and fantasy, known for the Earthsea books.'),
    (2, 'Octavia E. Butler', 'American science fiction author, the first to receive a MacArthur fellowship.'),
    (3, 'Italo Calvino', 'Italian writer of playful, inventive novels and short stories.');

INSERT IGNORE INTO books (id, title, published_year, summary, author_id) VALUES
    (1, 'A Wizard of Earthsea', 1968, 'A gifted boy learns magic and must face the shadow he set loose.', 1),
    (2, 'The Left Hand of Darkness', 1969, 'An envoy visits a planet whose people have no fixed sex.', 1),
    (3, 'Kindred', 1979, 'A young woman is pulled back in time to a plantation in Maryland.', 2),
    (4, 'Parable of the Sower', 1993, 'In a collapsing California, a teenager starts a new belief system.', 2),
    (5, 'Invisible Cities', 1972, 'Marco Polo describes imaginary cities to the emperor Kublai Khan.', 3);
```

**`application/models/Bookshelf/Author.php`**
```php
<?php

use Caligrafy\Model;

// One Author = one row of the authors table (Author::query() reads authors: the class name in lower case, plus s)
class Author extends Model {

    // one public property per column of the table
    public $id;
    public $name;
    public $bio;
    public $created_at;
    public $modified_at;
}
```

**`application/models/Bookshelf/Book.php`**
```php
<?php

use Caligrafy\Model;

// One Book = one row of the books table. Book::with('author') adds the row of authors whose id is author_id
class Book extends Model {

    // one public property per column of the table
    public $id;
    public $title;
    public $published_year;
    public $summary;
    public $author_id;
    public $created_at;
    public $modified_at;
}
```

Run the script:
```bash
docker compose exec dev-box php caligrafer.php sql application/models/Bookshelf/create_db.sql
```
```text
 application/models/Bookshelf/create_db.sql run on caligrafy
```
The primary key is always `id`. `Book::query()` reads the table `books` and `Author::query()` the table `authors`: the class name in lower case plus `s`. The foreign key `author_id` links a book to its author, and `Book::with('author')` reads that author with the book. Online, `php caligrafer.php deploy` runs every new or changed `create_db.sql` when the app starts. A later change to a table that holds data is a migration: see [step 9](#migration).

### <a name="capabilities"></a>2. Four capabilities

Caligrafer writes each class, ready to fill:
```bash
docker compose exec dev-box php caligrafer.php service Bookshelf/ListBooks --scope books:read --read-only
docker compose exec dev-box php caligrafer.php service Bookshelf/GetBook --scope books:read --read-only
docker compose exec dev-box php caligrafer.php service Bookshelf/ListAuthors --scope books:read --read-only
docker compose exec dev-box php caligrafer.php service Bookshelf/CreateBook --scope books:write
```
Each prints:
```text
 Created application/services/Bookshelf/ListBooks.php: capability 'list_books' (scope books:read)
 Fill in $rules and handle(), then serve it: a page (Route::page data), a form (Route::form), REST (Route::capability or Route::capabilities), MCP (Route::mcp)
```
The capability's name is the snake_case of the class name. Replace the content of the four files.

**`application/services/Bookshelf/ListBooks.php`**
```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;

// list_books: the catalog, sorted by title, 20 books per page, each with its author. Anyone may read it
#[Capability(
    name: 'list_books',
    description: 'Lists the books of the Bookshelf catalog, sorted by title, 20 per page, each with its author (id, name, bio). Give author_id to list only the books of one author, and page for the next pages. Returns data (the books), total, page, per_page and pages.',
    scope: 'books:read',
    readOnly: true,
    public: true
)]
class ListBooks extends Service
{
    public $rules = array('author_id' => 'integer', 'page' => 'integer');
    public $descriptions = array(
        'author_id' => 'Optional: only the books of this author',
        'page' => 'Optional: the page, 1 by default (20 books per page)'
    );

    public function handle(array $input, Context $context)
    {
        // two queries for the page (the count, then the books) and one for all their authors
        $query = Book::with('author')->orderBy('title');
        if (!empty($input['author_id'])) {
            $query->where('author_id', $input['author_id']);   // the value is bound, never pasted into the SQL
        }
        return $query->paginate(20, $input['page'] ?? 1);
    }
}
```

**`application/services/Bookshelf/GetBook.php`**
```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;
use Caligrafy\ServiceError;

// get_book: one book with its author, or "not found"
#[Capability(
    name: 'get_book',
    description: 'Returns one book of the catalog with its author (id, name, bio), by the id of the book.',
    scope: 'books:read',
    readOnly: true,
    public: true
)]
class GetBook extends Service
{
    public $rules = array('id' => 'required|integer');
    public $descriptions = array('id' => 'The id of the book');

    public function handle(array $input, Context $context)
    {
        $book = Book::with('author')->find($input['id']);
        if (!$book) {
            throw ServiceError::notFound("There is no book #{$input['id']}");
        }
        return $book;
    }
}
```

**`application/services/Bookshelf/ListAuthors.php`**
```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;

// list_authors: every author, sorted by name. Anyone may read it
#[Capability(
    name: 'list_authors',
    description: 'Lists the authors of the Bookshelf catalog, sorted by name: id, name and bio.',
    scope: 'books:read',
    readOnly: true,
    public: true
)]
class ListAuthors extends Service
{
    public function handle(array $input, Context $context)
    {
        return Author::query()->orderBy('name')->get();
    }
}
```

**`application/services/Bookshelf/CreateBook.php`**
```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;

// create_book: adds a book, with the same rules whoever calls it
#[Capability(
    name: 'create_book',
    description: 'Adds a book to the Bookshelf catalog and returns it with its id and its author. The author must already exist: use list_authors to find author_id.',
    scope: 'books:write',
    public: true   // for now: step 7 closes it
)]
class CreateBook extends Service
{
    public $rules = array(
        'title' => 'required|max_len,200',
        'published_year' => 'required|integer|min_numeric,1450|max_numeric,current_year',
        'summary' => 'max_len,2000',
        'author_id' => 'required|integer|exists,authors.id'
    );
    public $filters = array('title' => 'trim', 'summary' => 'trim');
    public $descriptions = array(
        'title' => 'The title of the book',
        'published_year' => 'The year it was first published, for example 1969 (not after this year)',
        'summary' => 'Optional: one or two sentences about the book',
        'author_id' => 'The id of its author (list_authors)'
    );

    public function handle(array $input, Context $context)
    {
        $id = Book::insert($input);   // one INSERT, every value bound; returns the id of the new book
        return Book::with('author')->find($id);
    }
}
```

What each part does:
+ `description` is what an AI agent reads to choose the tool: say what it does and what it returns.
+ `$rules` lists every input the capability accepts, with its [validation rules](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation). Only these inputs reach `handle()`. `exists,authors.id` refuses an author that is not in `authors`; `max_numeric,current_year` refuses a year after this one. `$filters` clean the inputs first; `$descriptions` describe them to clients and agents.
+ `scope` is what a token needs. `readOnly: true` marks a capability that changes nothing (only those can feed a page). `public: true` lets anyone call it without signing in: right for the reads, and for `create_book` only until [step 7](#secure).
+ `handle()` reads and writes with the [query builder](https://github.com/caligrafy/caligrafy-quill/wiki/Queries) (`Book::with('author')`, `Book::find()`, `Book::insert()`), every value bound, and returns data. It never draws a page, redirects or prints. It refuses with a `ServiceError` (`notFound`, `invalid`, `forbidden`, `conflict`).
+ `paginate(20, $input['page'] ?? 1)` returns `data` (the rows), `total`, `page`, `per_page` and `pages`. Always pass the page: REST, MCP and the command line have no query string.

Try them before any route:
```bash
docker compose exec dev-box php caligrafer.php capabilities
```
```text
 create_book                  public         writes    Adds a book to the Bookshelf catalog and returns it with its id and its author. The author must already exist: use list_authors to find author_id.
 get_book                     public         read      Returns one book of the catalog with its author (id, name, bio), by the id of the book.
 list_authors                 public         read      Lists the authors of the Bookshelf catalog, sorted by name: id, name and bio.
 list_books                   public         read      Lists the books of the Bookshelf catalog, sorted by title, 20 per page, each with its author (id, name, bio). Give author_id to list only the books of one author, and page for the next pages. Returns data (the books), total, page, per_page and pages.
```
(with the Tasks, Users and notification capabilities around them).
```bash
docker compose exec dev-box php caligrafer.php call create_book title=Dawn published_year=1987 author_id=2
```
```json
{
    "data": {
        "id": 6,
        "title": "Dawn",
        "published_year": 1987,
        "summary": null,
        "author_id": 2,
        "created_at": "2026-11-08 00:13:48",
        "modified_at": "2026-11-08 00:13:48",
        "author": {
            "id": 2,
            "name": "Octavia E. Butler",
            "bio": "American science fiction author, the first to receive a MacArthur fellowship.",
            "created_at": "2026-11-08 00:13:35",
            "modified_at": "2026-11-08 00:13:35"
        }
    }
}
```
```bash
docker compose exec dev-box php caligrafer.php call create_book title=Dawn
```
```json
{
    "error": {
        "code": "invalid",
        "message": "Some of the inputs are invalid",
        "fields": {
            "published_year": "The Published Year field is required",
            "author_id": "The Author Id field is required"
        }
    }
}
```
`call create_book title=Dawn published_year=1987 author_id=9` answers the field `"author_id": "There is no such author"`, `call get_book id=99` answers `{"error": {"code": "not_found", "message": "There is no book #99"}}`, and `call list_books author_id=2` lists the books of Octavia E. Butler, Dawn included.

### <a name="page"></a>3. A page with a form

Add these lines to `application/config/routing/web.php`, inside the `try` block, above the comment `// MUST NOT BE REMOVED - Routes need to be run after being defined` and its `Route::run();`:
```php
    // BOOKSHELF PAGES: rendered on the server with the data of the capabilities; the form calls create_book
    Route::page('/books', 'Bookshelf/books', ['data' => ['books' => 'list_books', 'authors' => 'list_authors'], 'query' => ['author_id']]);
    Route::form('/books', 'create_book', ['success' => '/books/{id}', 'flash' => 'Book added']);
    Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book'], 'notFound' => 'Bookshelf/notfound']);
```
+ `Route::page` shows a view with the results of read-only capabilities: in the view, `$books` is the answer of `list_books` and `$authors` the answer of `list_authors`, as arrays. The query string becomes inputs (`/books?author_id=2`, `?page=2`), and `query` gives the view `$author_id` (`''` when absent). On `/books/{id}`, the `id` of the address is the input of `get_book`; an unknown id renders the `notFound` view with status `404`.
+ `Route::form` takes the form's `POST`, checks its CSRF token, calls `create_book` with its fields as the person who sent it, and redirects to `success` (`{id}` comes from the new book) with the `flash` message. Refused input goes back to the form with a message per field ([Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form)).

Create the folder `application/views/Bookshelf` and three views. Views are [Pug](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views) in PHP mode: variables start with `$`, and strings join with `.`.

**`application/views/Bookshelf/books.pug`**
```pug
extends ../default/master/site

//- The catalog: Route::page gives it $books (list_books: a page of books) and $authors (list_authors).
//- The form posts to Route::form('/books', 'create_book'): a refusal comes back here with errors(), old() and flash('error')

block title
    | Bookshelf

block content
    section.cq-hero.cq-hero--page
        h1.cq-display Bookshelf
        p.cq-lead The books we love. The same catalog that the REST API and AI agents use.

    section.cq-band.cq-band--tight
        .cq-inner.cq-inner--narrow
            if flash('success')
                p.cq-alert(role='status')= flash('success')

            form(method='POST', action="{$home}books", novalidate)
                =csrf()
                .cq-form-grid.cq-form-grid--2
                    .cq-field
                        label(for='title') * Title
                        input#title.form-control(type='text', name='title', value=old('title'), maxlength='200')
                        if errors('title')
                            p.cq-field-error= errors('title')
                    .cq-field
                        label(for='author_id') * Author
                        select#author_id.form-select(name='author_id')
                            each $a in $authors
                                option(value=$a['id'], selected=$a['id'] == old('author_id'))= $a['name']
                        if errors('author_id')
                            p.cq-field-error= errors('author_id')
                    .cq-field
                        label(for='published_year') * Year
                        input#published_year.form-control(type='number', name='published_year', value=old('published_year'), placeholder='1969')
                        if errors('published_year')
                            p.cq-field-error= errors('published_year')
                .cq-field
                    label(for='summary') Summary
                    input#summary.form-control(type='text', name='summary', value=old('summary'), placeholder='Optional', maxlength='2000')
                button.btn.btn-primary(type='submit') Add book
            if flash('error')
                p.cq-field-error(role='alert')= flash('error')

    section.cq-band.cq-band--tight
        .cq-inner.cq-inner--narrow
            h2.cq-heading Books
            if $books['total'] == 0
                p.cq-empty-state No books here yet: add the first one above.
            else
                ul.cq-rows
                    each $b in $books['data']
                        li.cq-row
                            .cq-row-main
                                p.cq-row-title
                                    a(href="{$home}books/{$b['id']}")= $b['title']
                                p.cq-row-meta
                                    a(href="{$home}books?author_id={$b['author_id']}")= $b['author']['name']
                                    | , #{$b['published_year']}
                //- the next and previous pages keep the author of the address (?author_id=2)
                - $filter = $author_id !== '' ? '&author_id=' . (int) $author_id : '';
                p.cq-auth-note
                    | Page #{$books['page']} of #{$books['pages']}, #{$books['total']} books
                    if $books['page'] > 1
                        |  · 
                        a(href="{$home}books?page=" . ($books['page'] - 1) . $filter) Previous
                    if $books['page'] < $books['pages']
                        |  · 
                        a(href="{$home}books?page=" . ($books['page'] + 1) . $filter) Next
            p.cq-auth-note
                a(href="{$home}books") All books
```

**`application/views/Bookshelf/book.pug`**
```pug
extends ../default/master/site

//- One book: Route::page gives it $book (get_book: the book with its author)

block title
    = $book['title'] . ' · Bookshelf'

block content
    section.cq-hero.cq-hero--page
        h1.cq-display= $book['title']
        p.cq-lead
            | by #{$book['author']['name']}, #{$book['published_year']}

    section.cq-band.cq-band--tight
        .cq-inner.cq-inner--narrow
            if flash('success')
                p.cq-alert(role='status')= flash('success')
            p= $book['summary'] ?: 'No summary yet.'
            p.cq-auth-note
                a(href="{$home}books") All books
```

**`application/views/Bookshelf/notfound.pug`**
```pug
extends ../default/master/site

//- The notFound view of Route::page: $message is the message of the capability that refused (get_book)

block title
    | Not found · Bookshelf

block content
    section.cq-hero
        h1.cq-display Not found
        p.cq-lead= $message
        .cq-cta
            a.btn.btn-primary(href="{$home}books") All books
```

Open **http://localhost:8080/books**:
+ The five sample books and Dawn, added in step 2, are listed by title, each with its author: `Page 1 of 1, 6 books`.
+ Click an author: `/books?author_id=2` lists only the books of Octavia E. Butler.
+ Submit the form with an empty title and year: the page comes back with `Some of the inputs are invalid` under the button, `The Title field is required` and `The Published Year field is required` under their fields, and the author you chose still selected.
+ Add *The Dispossessed*, Ursula K. Le Guin, 1974: you land on `/books/7`, which shows the title, `by Ursula K. Le Guin, 1974` and `Book added`.
+ `http://localhost:8080/books/99` shows *Not found* and `There is no book #99`, with status `404`.

### <a name="rest"></a>4. A REST API

The Quickstart's `Route::capabilities('/capabilities')` already serves every capability to programs: `POST /capabilities/<name>` with the inputs as JSON, and `GET /capabilities` lists what the caller may use.
```bash
curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" \
     -d '{"title": "Wild Seed", "published_year": 1980, "author_id": 2}' \
     http://localhost:8080/capabilities/create_book
```
```json
{"data":{"id":8,"title":"Wild Seed","published_year":1980,"summary":null,"author_id":2,"created_at":"2026-11-08 00:14:45","modified_at":"2026-11-08 00:14:45","author":{"id":2,"name":"Octavia E. Butler","bio":"American science fiction author, the first to receive a MacArthur fellowship.","created_at":"2026-11-08 00:13:35","modified_at":"2026-11-08 00:13:35"}}}
```
For addresses of your own, add one `Route::capability` per address under the `BOOKSHELF PAGES` lines of `web.php`:
```php
    // BOOKSHELF API: the same capabilities, for other applications (JSON)
    Route::capability('GET', '/api/books', 'list_books');
    Route::capability('GET', '/api/books/{id}', 'get_book');
    Route::capability('POST', '/api/books', 'create_book');
    Route::capability('GET', '/api/authors', 'list_authors');
```
The query string and the `{id}` of the address become inputs:
```bash
curl -H "Accept: application/json" "http://localhost:8080/api/books?author_id=3"
curl -H "Accept: application/json" http://localhost:8080/api/books/3
curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" \
     -d '{"title": "Mind of My Mind", "published_year": 1977, "author_id": 2}' http://localhost:8080/api/books
```
The first answers `{"data":{"data":[{"id":5,"title":"Invisible Cities",...,"author":{"id":3,"name":"Italo Calvino",...}}],"total":1,"page":1,"per_page":20,"pages":1}}`, the second `{"data":{"id":3,"title":"Kindred",...,"author":{"id":2,"name":"Octavia E. Butler",...}}}`, the third `201` with the new book.

| Request | Status | Body |
| --- | --- | --- |
| a read, or a write of an existing record | `200` | `{"data": ...}` |
| a new record (`POST` on a capability that is not read-only) | `201` | `{"data": ...}` |
| refused input (`{"title": "No author", "published_year": 1990}`) | `422` | `{"error":{"code":"invalid","message":"Some of the inputs are invalid","fields":{"author_id":"The Author Id field is required"}}}` |
| unknown id | `404` | `{"error":{"code":"not_found","message":"There is no book #99"}}` |
| no sign-in or token for a capability that is not public | `401` | `{"error":{"code":"unauthenticated","message":"Sign in or send a personal access token"}}` |
| a token without the scope | `403` | `{"error":{"code":"forbidden","message":"This needs the scope books:write"}}` |

### <a name="agent"></a>5. Tools for AI agents

The Quickstart's `Route::mcp('/mcp')` makes every capability a tool. Give an agent a token with only the books scopes:
```bash
docker compose exec dev-box php caligrafer.php token create "books agent" --scopes books:read,books:write
```
```text
 Token #2 "books agent" created with books:read books:write

 cq_2_...

 It is shown only now: store it as a secret (Authorization: Bearer <token>).
```
Connect Claude Code with it:
```bash
claude mcp add --transport http bookshelf http://localhost:8080/mcp --header "Authorization: Bearer cq_2_..."
```
Ask "add The Lathe of Heaven by Ursula K. Le Guin, 1971, to my shelf": the agent calls `list_authors` to find her id, then `create_book`. The same call with `curl`:
```bash
curl -H "Authorization: Bearer cq_2_..." -H "Content-Type: application/json" \
     -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"create_book","arguments":{"title":"The Lathe of Heaven","published_year":1971,"author_id":1}}}' \
     http://localhost:8080/mcp
```
The answer has `"isError":false` and the new book, with its author, in `structuredContent`. Without `author_id`, it has `"isError":true` and the same `fields` as REST. `tools/list` shows the books tools and the public ones; the user administration tools stay hidden from this token. Without a token, `/mcp` answers `401` with a `WWW-Authenticate: Bearer` header and the JSON-RPC error `{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Unauthorized: send Authorization: Bearer <personal access token>"}}` (2.19.1; before, a browser's session cookie got a `403` CSRF page instead).

### <a name="client"></a>6. The JavaScript client, for Vue apps and page scripts

Generate the client again after every change to a capability:
```bash
docker compose exec dev-box php caligrafer.php client
```
```text
 public/js/capabilities.js written: 22 capabilities, calls /capabilities (Route::capabilities('/capabilities') in web.php)
 import { createBook, CapabilityError } from './capabilities.js'
```
Each capability is a function (`list_books` becomes `listBooks`). In a page of the application it sends the visitor's session; elsewhere, `configure({ baseUrl, token })`:
```js
import { listBooks, createBook, CapabilityError } from './capabilities.js'

const shelf = await listBooks({ author_id: 2, page: 1 })
console.log(shelf.total, shelf.data[0].title, shelf.data[0].author.name)
try {
  await createBook({ title: 'No author', published_year: 1990 })
} catch (e) {
  if (e instanceof CapabilityError) console.log(e.status, e.fields.author_id)   // 422 The Author Id field is required
}
```
Vue apps: see [Vue apps: the JS client](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#client).

### <a name="secure"></a>7. Before you go online: sign-in

`public: true` on `create_book` lets anyone add books. Close it: readers keep the catalog, and only people who signed in, or a program with a token, add books.

1. Create the `users` table of the authentication module:
    ```bash
    docker compose exec dev-box php caligrafer.php sql application/models/Auth/create_db.sql
    ```
2. In `application/config/routing/web.php`, remove the `// ` in front of `Auth::authentication('User', 'users');` near the top, and add `Route::auth` as the first line of the `BOOKSHELF PAGES` lines:
    ```php
        Auth::authentication('User', 'users');
    ```
    ```php
        // BOOKSHELF PAGES: rendered on the server with the data of the capabilities; the form calls create_book
        Route::auth(['home' => '/books']);
    ```
    `Route::auth` declares `/login`, `/logout`, `/register` and `/notAuthorized`, with the sign-in pages of the [authentication module](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication). After signing in, people land on `/books`.
3. In `application/services/Bookshelf/CreateBook.php`, remove `public: true` and its comment (and the comma before it):
    ```php
    #[Capability(
        name: 'create_book',
        description: 'Adds a book to the Bookshelf catalog and returns it with its id and its author. The author must already exist: use list_authors to find author_id.',
        scope: 'books:write'
    )]
    ```

Now:
+ A visitor who submits the form on `/books` is sent to `/login`.
+ `POST /api/books` without a token gets `401` and `Sign in or send a personal access token`.
+ The `books agent` token still adds books (`201`): it has `books:write`.
+ Create an account at `/register` (usernames are letters and digits, for example `sam42`; to sign in with an email instead, see [Signing in with an email](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#emailsignin)); you are sent to `/login`. Sign in: you land on `/books`, and the form adds the book.

`docker compose exec dev-box php caligrafer.php audit` lists every change and every refusal: when, through which channel, who, which capability:
```text
 2026-11-08 00:15:31  web   user   1            create_book                  ok
 2026-11-08 00:15:30  web   guest  -            register_user                ok
 2026-11-08 00:15:18  rest  token  2            create_book                  ok
 2026-11-08 00:15:18  rest  guest  -            create_book                  unauthenticated  Sign in or send a personal access token
 2026-11-08 00:15:18  web   guest  -            create_book                  unauthenticated  Sign in or send a personal access token
```
To keep a capability for administrators (`permissions` of 1 or more in `users`), add `level: 1` to its `#[Capability]`. The Tasks example is still public: remove its `public: true` the same way, or remove the example.

### <a name="test"></a>8. A test

```bash
docker compose exec dev-box php caligrafer.php test make Bookshelf
```
```text
 tests/BookshelfTest.php written: php caligrafer.php test Bookshelf
```
Replace the content of **`tests/BookshelfTest.php`**:
```php
<?php

use Caligrafy\Testing\TestCase;

/**
 * php caligrafer.php test Bookshelf
 */
final class BookshelfTest extends TestCase
{
    public function testASignedInPersonAddsABook(): void
    {
        $book = $this->call('create_book', ['title' => 'Tehanu', 'published_year' => 1990, 'author_id' => 1], $this->user(1));
        $this->assertSame('Tehanu', $book['title']);
        $this->assertSame('Ursula K. Le Guin', $this->call('get_book', ['id' => $book['id']])['author']['name']);
    }

    public function testAVisitorCannotAddABook(): void
    {
        $this->assertCapabilityFails('unauthenticated', 'create_book', ['title' => 'Tehanu', 'published_year' => 1990, 'author_id' => 1], 'guest');
    }

    public function testABookNeedsAnAuthorThatExists(): void
    {
        $error = $this->assertCapabilityFails('invalid', 'create_book', ['title' => 'Tehanu', 'published_year' => 1990], $this->user(1));
        $this->assertArrayHasKey('author_id', $error->fields);
        $error = $this->assertCapabilityFails('invalid', 'create_book', ['title' => 'Tehanu', 'published_year' => 1990, 'author_id' => 999], $this->user(1));
        $this->assertSame('There is no such author', $error->fields['author_id']);
    }
}
```
```bash
docker compose exec dev-box php caligrafer.php test
```
```text
PHPUnit 12.5.44 by Sebastian Bergmann and contributors.

Runtime:       PHP 8.5.12

...                                                                 3 / 3 (100%)

Time: 00:00.077, Memory: 20.00 MB

OK (3 tests, 7 assertions)
```
Each test runs in a transaction that is rolled back: the books it adds do not stay. More in [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App).

### <a name="migration"></a>9. Later: change the table with a migration

Once `books` holds data (on your computer or online), never edit its `create_db.sql` to change it: write a migration, a numbered SQL file that runs once. Give books an optional ISBN that two books never share:
```bash
docker compose exec dev-box php caligrafer.php migrate make add_books_isbn
```
```text
 application/migrations/20261108001545_add_books_isbn.sql written: add its SQL, then php caligrafer.php migrate
```
Add the SQL at the end of the file it wrote (one statement: the column and its unique index are added together, or not at all):
```sql
-- add_books_isbn
-- Runs once (php caligrafer.php migrate, and at every deploy). Never edit it after it ran: write a new one.

ALTER TABLE books
    ADD COLUMN isbn VARCHAR(20) NULL AFTER summary,
    ADD UNIQUE KEY uq_books_isbn (isbn);
```
```bash
docker compose exec dev-box php caligrafer.php migrate
```
```text
 OK   20261108001545_add_books_isbn.sql

 1 migration(s) run on caligrafy
```
Then give the code the new column:
1. In `application/models/Bookshelf/Book.php`, add `public $isbn;` after `public $summary;`.
2. Make `application/services/Bookshelf/CreateBook.php` read (the `isbn` input, its filter and its description, and an empty ISBN saved as `NULL`, which the unique index allows on many books):
    ```php
    <?php

    use Caligrafy\Capability;
    use Caligrafy\Context;
    use Caligrafy\Service;

    // create_book: adds a book, with the same rules whoever calls it
    #[Capability(
        name: 'create_book',
        description: 'Adds a book to the Bookshelf catalog and returns it with its id and its author. The author must already exist: use list_authors to find author_id. The ISBN is optional and unique.',
        scope: 'books:write'
    )]
    class CreateBook extends Service
    {
        public $rules = array(
            'title' => 'required|max_len,200',
            'published_year' => 'required|integer|min_numeric,1450|max_numeric,current_year',
            'summary' => 'max_len,2000',
            'isbn' => 'alpha_numeric_dash|max_len,20|unique,books.isbn',
            'author_id' => 'required|integer|exists,authors.id'
        );
        public $filters = array('title' => 'trim', 'summary' => 'trim', 'isbn' => 'trim');
        public $descriptions = array(
            'title' => 'The title of the book',
            'published_year' => 'The year it was first published, for example 1969 (not after this year)',
            'summary' => 'Optional: one or two sentences about the book',
            'isbn' => 'Optional: its ISBN, digits and dashes, for example 978-0-441-47812-5; two books never share one',
            'author_id' => 'The id of its author (list_authors)'
        );

        public function handle(array $input, Context $context)
        {
            // an empty ISBN is no ISBN: NULL, which the unique index allows on many books
            $input['isbn'] = ($input['isbn'] ?? '') === '' ? null : $input['isbn'];
            $id = Book::insert($input);   // one INSERT, every value bound; returns the id of the new book
            return Book::with('author')->find($id);
        }
    }
    ```
3. In `application/views/Bookshelf/books.pug`, add the field after the year's `.cq-field`, at the same depth:
    ```pug
                        .cq-field
                            label(for='isbn') ISBN
                            input#isbn.form-control(type='text', name='isbn', value=old('isbn'), placeholder='Optional', maxlength='20')
                            if errors('isbn')
                                p.cq-field-error= errors('isbn')
    ```

A second book with the same ISBN is now refused on every channel with `"isbn": "This isbn is already used"`. Online, the deploy runs the migrations that never ran. More in [Migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations).

### Check

+ `php caligrafer.php capabilities` lists `list_books`, `get_book` and `list_authors` as `public` and `read`, and `create_book` as `books:write` and `writes`.
+ `/books` lists the books with their authors; an empty form shows a message under each required field; a new book opens its own page with `Book added`.
+ `curl http://localhost:8080/api/books` answers `200`; a `POST` without a token answers `401`; with the `books agent` token, `201`.
+ `php caligrafer.php test` ends with `OK`.
+ `php caligrafer.php migrate status` shows `add_books_isbn` as run.
## Common mistakes

+ **A capability without `--scope`.** `service` then writes `scope: ''`: the capability needs no scope, so any token can call it. Give every capability a scope.
+ **A foreign key without `exists`.** Without `exists,authors.id` in `$rules`, a book with an unknown author reaches the database, which refuses it with a foreign key error instead of a message under the field.
+ **`paginate()` without a page in a capability.** It then reads `$_GET`, which REST, MCP and the command line do not have: pass `$input['page'] ?? 1`, with `'page' => 'integer'` in `$rules`.
+ **A page fed by a capability that writes.** `Route::page` data accepts only `readOnly` capabilities: it stops with an error otherwise.
+ **`flash()`, `errors()` and `old()` last one request.** Point `success` (and `back`) at the page that shows them.
+ **A `POST` with `curl` without `Accept: application/json`.** It is treated as a form without a CSRF token: `[ERROR 3000]` (403).
+ **Editing a `create_db.sql` that already ran online** to change a table: the change is a migration (step 9).
+ **Model code outside a capability.** Pages, forms, custom requests (`Route::action`) and scripts call capabilities; only capabilities read and write models.
## <a name="next"></a>What you built

One feature, written once in four small classes, used from a web page, by other programs and by AI agents, with the same rules everywhere. Next:
+ [How Caligrafy works](https://github.com/caligrafy/caligrafy-quill/wiki/How-Caligrafy-Works): the ideas behind it.
+ [Build Once: Services, Capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP): every option of a capability, tokens, MCP over stdio, the audit log.
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes): forms that change and delete (`update_book`, `delete_book`), sign-in options, webhooks and downloads.
+ [Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models), [Relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships) and [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries): loans, tags, filters and search.
+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online).

<br/><br/>
>[Next: Build Once: Services, Capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once%3A-Services%2C-Capabilities-and-MCP -->

**Build once, experience everywhere** is what Caligrafy is for. A feature is written once, as a **capability**: a small
PHP class (a **service**) that declares its inputs, checks who is asking, does the work and returns data. Every way of
reaching your application is a **channel** that calls the same capability: your Pug pages (`Route::page`,
`Route::form`), a REST API, the JavaScript client of your Vue apps, and AI agents over MCP. A rule written once
behaves the same for a person, a phone, a program and an agent.

**Since 2.26.0**: a write capability declared without a `scope` needs, from a token, the scope named after it (or `*`); a public read-only capability may declare `cache: <seconds>` to be served from the production image's memory ([performance](https://github.com/caligrafy/caligrafy-quill/wiki/Performance-and-Deployment)); and the experimental async server answers the capabilities channel from processes that keep the app in memory (`ASYNC=on`).
## <a name="overview"></a>How it fits together

| Channel | How it calls a capability | Who is calling |
| --- | --- | --- |
| Pug pages | `Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book']])`; forms with `Route::form('/books', 'create_book', [...])` | the person who opens the page (signed in, or a visitor) |
| REST | `Route::capability('POST', '/api/books', 'create_book')`, or every capability under `Route::capabilities('/capabilities')` | a personal access token, or the signed-in user |
| Vue apps, the Vite SPA, Node | the generated JS client (`php caligrafer.php client`), on `Route::capabilities('/capabilities')` | the signed-in user (session and CSRF token), or a token |
| AI agents | MCP: `Route::mcp('/mcp')` over HTTP, or `php caligrafer.php mcp` over stdio | a personal access token (stdio: also your own full access) |
| The command line, scripts, jobs | `php caligrafer.php call create_book ...`, `Capabilities::call()`, the queue and the scheduler | full access, or a token |

A capability declared `webOnly: true` has one channel instead of all of them: [`Route::action`](#webonly), for what only a
browser can do.

Every call goes through the same steps, in this order:

1. **Find** the capability (`not_found`, 404).
2. **Check who calls**: public, or signed in or a token (`unauthenticated`, 401), with the right scope and level
   (`forbidden`, 403).
3. **Keep, filter and validate** the declared inputs (`invalid`, 422, with a message per field).
4. **Run** `handle()`.
5. **Audit**: every refusal, and every success of a capability that changes data, is written to the audit log.

**Only capabilities touch models**: pages, forms, REST, agents and the controllers of older code all go through them, so
the rules exist once.
## With Claude

Ask for the feature with the `new-capability` skill of the Claude Code plugin: its name, its scope, and what it does.

```text
/caligrafy-quill:new-capability create_book books:write: add a book (title, published year, summary, author) and return it
/caligrafy-quill:new-capability delete_book books:write destructive: only administrators (level 1)
```

Claude:
+ runs `php caligrafer.php service <Folder>/<Name> --scope <scope>` and fills
  `application/services/<Folder>/<Name>.php`: a `description` written for an AI agent, `$rules` for every input,
  `handle()` with the query builder, `ServiceError` refusals, `readOnly` / `destructive` / `level` / `public`;
+ adds the channels you need to `application/config/routing/web.php` (`Route::page`, `Route::form`,
  `Route::capability`, `Route::capabilities`, `Route::mcp`) and runs `php caligrafer.php client` for a Vue app;
+ creates a token only when an agent or a program needs one, shows it once, and never writes it in a file;
+ checks every channel (`capabilities`, `call`, REST with `curl`, MCP `tools/list` and `tools/call`, `audit`), and
  writes a test in `tests/` (`php caligrafer.php test`).

**Check** before you say OK:
+ `php caligrafer.php capabilities` lists it with the scope and the flag you expect (`read`, `writes`, `destroys`);
+ the description says what it does and what it returns;
+ an invalid input gives a message per field, on the command line, over REST and over MCP alike;
+ a token without the scope gets `403` over REST, and does not see the tool in MCP `tools/list`;
+ `php caligrafer.php audit --capability <name>` shows the calls.
## By hand

This builds the Bookshelf capabilities and serves them on every channel. It starts from the tables and models of
[Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models), `get_book` of
[Relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships) and `list_books` of
[Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries#capability). The server is the Docker server of the
[Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart), at `http://localhost:8080`; run each
`php caligrafer.php` command in its container, as written (without Docker, drop `docker compose exec dev-box` and use
your own address).

### <a name="setup"></a>1. The framework tables

Run:
```bash
docker compose exec dev-box php caligrafer.php platform install
```
```text
 Framework tables ready: caligrafy_tokens, caligrafy_audit, caligrafy_job_runs, the notifications tables, caligrafy_jobs, caligrafy_cache and caligrafy_migrations
```
It is safe to run again. `docker compose exec dev-box php caligrafer.php doctor --only database` then shows
`OK    Framework tables: tokens, audit log, job runs, jobs, cache and migrations installed`.

### <a name="service"></a>2. Write the capabilities

1. Run:
    ```bash
    docker compose exec dev-box php caligrafer.php service Bookshelf/CreateBook --scope books:write
    ```
    ```text
     Created application/services/Bookshelf/CreateBook.php: capability 'create_book' (scope books:write)
    ```
2. Make `application/services/Bookshelf/CreateBook.php` read:
    ```php
    <?php

    use Caligrafy\Capability;
    use Caligrafy\Context;
    use Caligrafy\Service;

    #[Capability(
        name: 'create_book',
        description: 'Adds a book to the Bookshelf catalog and returns it with its id and its author. The author must already exist: use list_authors to find author_id.',
        scope: 'books:write'
    )]
    class CreateBook extends Service
    {
        public $rules = array(
            'title' => 'required|max_len,200',
            'published_year' => 'required|integer|min_numeric,1450|max_numeric,current_year',
            'summary' => 'max_len,2000',
            'author_id' => 'required|integer|exists,authors.id'
        );

        public $filters = array(
            'title' => 'trim',
            'summary' => 'trim'
        );

        public $descriptions = array(
            'title' => 'The title of the book',
            'published_year' => 'The year it was first published, for example 1969 (not after this year)',
            'summary' => 'Optional: one or two sentences about the book',
            'author_id' => 'The id of its author (list_authors)'
        );

        public function handle(array $input, Context $context)
        {
            $id = Book::insert($input);   // one INSERT, every value bound; returns the id of the new book
            return Book::with('author')->find($id);
        }
    }
    ```
3. Run `docker compose exec dev-box php caligrafer.php service Bookshelf/DeleteBook --scope books:write`, then make
   `application/services/Bookshelf/DeleteBook.php` read:
    ```php
    <?php

    use Caligrafy\Capability;
    use Caligrafy\Context;
    use Caligrafy\Service;
    use Caligrafy\ServiceError;

    #[Capability(
        name: 'delete_book',
        description: 'Deletes a book of the catalog for good, with its loans and its tags. Returns the id of the deleted book.',
        scope: 'books:write',
        level: 1,
        destructive: true
    )]
    class DeleteBook extends Service
    {
        public $rules = array('id' => 'required|integer');

        public $descriptions = array('id' => 'The id of the book to delete');

        public function handle(array $input, Context $context)
        {
            if (Book::where('id', $input['id'])->delete() === 0) {
                throw ServiceError::notFound('There is no book #' . $input['id']);
            }
            return array('deleted' => (int) $input['id']);
        }
    }
    ```
    `level: 1`: a signed-in person needs `permissions` 1 or more in the `users` table (an administrator).
    `destructive: true`: agents ask the user before they call it.
4. Run `docker compose exec dev-box php caligrafer.php capabilities`. Among the framework's own capabilities
   (users, notifications, the queue), it lists:
    ```text
     create_book                  books:write    writes    Adds a book to the Bookshelf catalog and returns it with its id and its author. The author must already exist: use list_authors to find author_id.
     delete_book                  books:write    destroys  Deletes a book of the catalog for good, with its loans and its tags. Returns the id of the deleted book.
     get_book                     public         read      Returns one book by its id, with its author, its tags and its loans.
     list_books                   public         read      Lists the books of the Bookshelf catalog, sorted by title, 20 per page, ... (cut here)
    ```
5. Call it from the command line (full access, with the checks and the audit):
    ```bash
    docker compose exec dev-box php caligrafer.php call create_book '{"title": "The Dispossessed", "published_year": 1974, "author_id": 1}'
    ```
    ```json
    {
        "data": {
            "id": 6,
            "title": "The Dispossessed",
            "published_year": 1974,
            "summary": null,
            "author_id": 1,
            "created_at": "2026-11-07 23:17:13",
            "modified_at": "2026-11-07 23:17:13",
            "author": {
                "id": 1,
                "name": "Ursula K. Le Guin",
                "bio": "American author of science fiction and fantasy, known for the Earthsea books.",
                "created_at": "2026-11-07 23:16:40",
                "modified_at": "2026-11-07 23:16:40"
            }
        }
    }
    ```
    `call create_book title=Dune` answers the field messages:
    ```json
    {
        "error": {
            "code": "invalid",
            "message": "Some of the inputs are invalid",
            "fields": {
                "published_year": "The Published Year field is required",
                "author_id": "The Author Id field is required"
            }
        }
    }
    ```
    `call create_book title=Dune --guest` (as a visitor) answers `"code": "unauthenticated"`.

### <a name="web"></a>3. Pages

In `application/config/routing/web.php`, inside the `try` block and before `Route::run();`, add:
```php
    // BOOKSHELF: the pages
    Route::page('/books', 'Bookshelf/books', ['data' => ['books' => 'list_books']]);
    Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book'], 'notFound' => 'Bookshelf/notfound']);
```
Write the three views. `application/views/Bookshelf/books.pug`:
```pug
extends ../default/master/site

block title
  | Books · Bookshelf

block content
  section.cq-hero.cq-hero--page
    h1.cq-display Books
    p.cq-lead= $books['total'] . ' books in the catalog'

  section.cq-band
    .cq-inner
      if flash('success')
        .cq-alert.cq-alert--success= flash('success')
      if $books['data']
        ul.cq-rows
          each $book in $books['data']
            li.cq-row
              a(href=$home . 'books/' . $book['id'])= $book['title']
              span.cq-muted= ' by ' . $book['author']['name']
      else
        .cq-empty-state No books yet.
```
`application/views/Bookshelf/book.pug`:
```pug
extends ../default/master/site

block title
  | #{$book['title']} · Bookshelf

block content
  section.cq-hero.cq-hero--page
    h1.cq-display= $book['title']
    p.cq-lead= $book['author']['name'] . ', ' . $book['published_year']

  section.cq-band
    .cq-inner
      if flash('success')
        .cq-alert.cq-alert--success= flash('success')
      p= $book['summary']
      p= 'Tags: ' . implode(', ', array_column($book['tags'], 'name'))
```
`application/views/Bookshelf/notfound.pug`, the page of a book that does not exist (`$message` is the refusal of
`get_book`):
```pug
extends ../default/master/site

block title
  | Not found · Bookshelf

block content
  section.cq-hero
    h1.cq-display Not found
    p.cq-lead= $message
    .cq-cta
      a.btn.btn-primary(href=$home . 'books') All books
```
Open `http://localhost:8080/books`: the books, each with its author. `http://localhost:8080/books/3` shows *Kindred*,
*Octavia E. Butler, 1979*; `/books/99` shows *Not found*, *There is no book #99*, with status 404.

+ A page's `data` capabilities must be read-only. They run as the person who opens the page, with the route
  variables (`{id}`) and the query string as inputs, the route variables winning. The view gets plain arrays
  (`$book['title']`), plus `$authorized` and `$user`, and of the query string only the names you list in `query`.
+ A capability that refuses a visitor sends them to sign in (with the authentication module), or answers 403 or 404.
+ A form posts to a capability:
  `Route::form('/books', 'create_book', ['success' => '/books/{id}', 'flash' => 'Added {title}'])`. It calls the
  capability as the signed-in person; on invalid input it goes back, and the view shows `errors('title')`,
  `old('title')` and `flash('error')`. Sign-in pages come from `Route::auth()`. Both are on
  [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form) and
  [Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#routeauth).

### <a name="tokens"></a>4. A personal access token

A program or an agent proves who it is with a **personal access token**: it has a name, **scopes** (what it may do)
and, optionally, an owner and an expiry, and it can be revoked on its own. Run:
```bash
docker compose exec dev-box php caligrafer.php token create "Bookshelf agent" --scopes books:read,books:write
```
```text
 Token #1 "Bookshelf agent" created with books:read books:write

 cq_1_<40 hexadecimal characters>

 It is shown only now: store it as a secret (Authorization: Bearer <token>).
```
Keep it in your terminal for the next steps: `TOKEN=cq_1_...` (the whole token). Make a second one that can only read,
to see the refusals: `token create "Reader" --scopes books:read --expires 90` (it prints `..., expires <date in 90 days>`).

`docker compose exec dev-box php caligrafer.php token list` shows them, never their secret:
```text
 #2    active   Reader                         books:read  never used
 #1    active   Bookshelf agent                books:read books:write  never used
```

### <a name="rest"></a>5. REST

In `web.php`, before `Route::run();`, add:
```php
    // BOOKSHELF: REST
    Route::capability('GET', '/api/books', 'list_books');
    Route::capability('GET', '/api/books/{id}', 'get_book');
    Route::capability('POST', '/api/books', 'create_book');
    Route::capability('DELETE', '/api/books/{id}', 'delete_book');
```
The route variables (`{id}`) become inputs. Then run (a `POST` with neither a token nor `Accept: application/json`
is taken for a form and answers `403` `[ERROR 3000]`):
```bash
curl -s http://localhost:8080/api/books/3
# {"data":{"id":3,"title":"Kindred","published_year":1979,...}}            200: get_book is public

curl -s -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d '{"title": "Dune"}' http://localhost:8080/api/books
# {"error":{"code":"unauthenticated","message":"Sign in or send a personal access token"}}   401

curl -s -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" \
     -d '{"title": "The Lathe of Heaven", "published_year": 1971, "author_id": 1}' http://localhost:8080/api/books
# {"data":{"id":7,"title":"The Lathe of Heaven","published_year":1971,"summary":null,"author_id":1,...,"author":{"id":1,"name":"Ursula K. Le Guin",...}}}   201

curl -s -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" \
     -d '{"title": "X", "published_year": 1971, "author_id": 42}' http://localhost:8080/api/books
# {"error":{"code":"invalid","message":"Some of the inputs are invalid","fields":{"author_id":"There is no such author"}}}   422
```
With the Reader token, the same `POST` answers
`{"error":{"code":"forbidden","message":"This needs the scope books:write"}}` (403).

+ **Requests**: a JSON body, form fields, or the query string for `GET`. Then the route variables, which win.
+ **Responses**: `200` with `{"data": ...}`, `201` when a `POST` changes data, or `{"error": {"code", "message",
  "fields"}}` with 401 (and `WWW-Authenticate: Bearer`), 403, 404, 409 or 422.
+ **Who calls**: `Authorization: Bearer <token>`, or the session of a signed-in person. A call made with the session
  that changes data needs the session's CSRF token in an `X-CSRF-Token` header (403 `Missing or invalid CSRF token:
  send the X-CSRF-Token header` otherwise); the JS client sends it.

### <a name="mcp"></a>6. AI agents: MCP

[MCP](https://modelcontextprotocol.io) (the Model Context Protocol) is how AI agents such as Claude use tools. With
`Route::mcp('/mcp')` every capability is a tool: its name, its description, its input schema, and hints that say
whether it only reads (`readOnlyHint`) or destroys data (`destructiveHint`). An agent sees only the tools its token
allows, and its calls go through the same checks, validation and audit as everyone else's.

In `web.php`, before `Route::run();`, add:
```php
    Route::mcp('/mcp');   // AI agents: personal access tokens only
```
Without a token it answers `401` and a JSON-RPC error (2.19.1):
```bash
curl -s -i -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' http://localhost:8080/mcp
```
```text
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error="invalid_token", error_description="Send a personal access token: php caligrafer.php token create"
Content-Type: application/json

{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Unauthorized: send Authorization: Bearer <personal access token>"}}
```
Talk to it as an agent does, with `curl` and the token. Each request is one JSON-RPC message:
```bash
curl -s -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" \
     -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}' \
     http://localhost:8080/mcp
```
```json
{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-06-18","capabilities":{"tools":{"listChanged":false}},"serverInfo":{"name":"caligrafy-app","title":"caligrafy-app","version":"2.25.0"},"instructions":"Tools are the capabilities of this application that your token allows. Tools marked destructive delete or overwrite data: confirm with the user first."}}
```
(`serverInfo.name` is your `APP_NAME`.) Then the tools:
```bash
curl -s -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" \
     -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' http://localhost:8080/mcp
```
The list has `create_book`, `delete_book` (`"destructiveHint": true`), `get_book` and `list_books`
(`"readOnlyHint": true`), and the framework's public `register_user` (which refuses every channel but web pages and
the command line). Each tool looks like this one:
```json
{"name": "create_book", "title": "Create book", "description": "Adds a book to the Bookshelf catalog and returns it with its id and its author. The author must already exist: use list_authors to find author_id.",
 "inputSchema": {"type": "object", "properties": {
    "title": {"type": "string", "maxLength": 200, "description": "The title of the book"},
    "published_year": {"type": "integer", "minimum": 1450, "maximum": 2026, "description": "The year it was first published, for example 1969 (not after this year)"},
    "summary": {"type": "string", "maxLength": 2000, "description": "Optional: one or two sentences about the book"},
    "author_id": {"type": "integer", "description": "The id of its author (list_authors)"}},
  "additionalProperties": false, "required": ["title", "published_year", "author_id"]},
 "annotations": {"readOnlyHint": false, "destructiveHint": false, "openWorldHint": false}}
```
With the Reader token, `create_book` and `delete_book` are not in the list. Call a tool:
```bash
curl -s -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" \
     -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"create_book","arguments":{"title":"Dune"}}}' \
     http://localhost:8080/mcp
```
```json
{"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"{\"error\":{\"code\":\"invalid\",\"message\":\"Some of the inputs are invalid\",\"fields\":{\"published_year\":\"The Published Year field is required\",\"author_id\":\"The Author Id field is required\"}}}"}],"isError":true}}
```
A refused call is a tool result with `"isError": true` and the same fields as REST, so the agent can correct itself.
A successful one has `"isError": false`, the data as JSON in `content[0].text`, and the object in `structuredContent`.

**Connect Claude Code** to the server:
```bash
claude mcp add --transport http bookshelf http://localhost:8080/mcp --header "Authorization: Bearer cq_..."
```
**Over stdio**, a local agent starts the server itself, in the project folder:
```bash
claude mcp add bookshelf -- docker compose exec -T dev-box php caligrafer.php mcp
```
Without a token, stdio has full access, like any command you run yourself (it says so on stderr:
`caligrafer mcp: no token, full local access (set CALIGRAFY_TOKEN to limit it)`). With `CALIGRAFY_TOKEN=cq_...` (or
`--token cq_...`) it has the rights of that token.

### <a name="client"></a>7. Vue apps and the Vite SPA: the JS client

In `web.php`, before `Route::run();`, add:
```php
    Route::capabilities('/capabilities');   // GET lists, POST /capabilities/{name} calls: the JS client uses it
```
Generate the client: one JavaScript function per capability. Run:
```bash
docker compose exec dev-box php caligrafer.php client public/js/capabilities.js
```
```text
 public/js/capabilities.js written: 17 capabilities, calls /capabilities (Route::capabilities('/capabilities') in web.php)
 import { createBook, CapabilityError } from './capabilities.js'
```
(For a Vite SPA, write it in `public/<app>/src/capabilities.js`.) Use it in your app:
```js
import { createBook, listBooks, CapabilityError } from './capabilities.js'

try {
  const book = await createBook({ title: this.title, published_year: this.year, author_id: this.authorId })
  this.books = (await listBooks({ author_id: book.author_id })).data
} catch (e) {
  if (e instanceof CapabilityError && e.code === 'invalid') this.errors = e.fields   // { published_year: '...' }
  else throw e
}
```
+ In a page of the application it uses the **session**: the cookie, and the CSRF token it reads once from
  `GET /capabilities`. No key is ever in the bundle.
+ From Node or another site, give it a token: `configure({ baseUrl: 'http://localhost:8080', token: process.env.CALIGRAFY_TOKEN })`.
+ Run `client` again after you add or change a capability.

`GET /capabilities` answers what the caller may call: `{"data": [{"name", "description", "scope", "level", "readOnly",
"destructive", "public", "input"}, ...], "csrf": "<the session's CSRF token>"}`. `POST /capabilities/get_book` with
`{"id": 3}` calls `get_book`.

### <a name="audit"></a>8. The audit log

Run:
```bash
docker compose exec dev-box php caligrafer.php audit --capability create_book --limit 5
```
```text
 2026-11-07 23:18:39  mcp   token  1            create_book                  invalid  Some of the inputs are invalid
 2026-11-07 23:18:25  rest  token  1            create_book                  invalid  Some of the inputs are invalid
 2026-11-07 23:18:25  rest  token  1            create_book                  ok
 2026-11-07 23:18:25  rest  token  2            create_book                  forbidden  This needs the scope books:write
 2026-11-07 23:18:25  rest  guest  -            create_book                  unauthenticated  Sign in or send a personal access token
```
Each row: when, the channel (`web`, `rest`, `mcp`, `cli`), who (`user`, `token`, `key`, `cli`, `guest`, or `schedule`
and `queue` for jobs) and its id, the capability, the outcome and a short note. Inputs are never stored. A read-only
capability is written only when it is refused.

**Check** the whole chapter:
+ `capabilities` lists your four capabilities with the right flags;
+ the same invalid `create_book` gives the same `fields` from `call`, REST and MCP;
+ the Reader token gets 403 from REST and does not see `create_book` in `tools/list`;
+ `audit` shows the calls of every channel.
## <a name="experiences"></a>One look on every device

`public/css/tokens.css` defines the Caligrafy look as CSS custom properties (`--cq-color-ink`, `--cq-space-3`,
`--cq-touch-target`...), from `public/css/tokens.json`, so Pug pages, Vue apps and the SPA share it. The default
layout, the Vue app template and the SPA template include it. It gives larger touch targets on touch screens
(`pointer: coarse`), safe-area padding when the app is installed to the home screen, and `.cq-split` (one column on
phones, a list and its detail side by side from tablets up). Build each screen from the
[page components](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#pagecomponents), and combine it with
[install to home screen](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#install) for a mobile app on the
same capabilities.
## <a name="test"></a>Testing a capability

Your tests call capabilities the way the channels do, with the checks, the validation and the audit, in a
transaction that is rolled back:
```php
$book = $this->call('create_book', ['title' => 'Tehanu', 'published_year' => 1990, 'author_id' => $authorId], $this->user(7));
$this->assertCapabilityFails('unauthenticated', 'create_book', ['title' => 'Tehanu'], 'guest');
$answer = $this->action('open_author_books', ['author_id' => 3])->describe();   // a web-only capability: what it answers
```
Run them with `php caligrafer.php test`: [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App).
A capability asks for what it uses in its constructor ([Dependency injection](https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection)),
and can run later as a [background job](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs) or on a
[schedule](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs).
## Reference

### `#[Capability(...)]`

| Argument | Default | Meaning |
| --- | --- | --- |
| `name` | (required) | snake_case, letters, digits and `_`, starting with a letter, at most 64 characters; unique in the application. How every channel calls it |
| `description` | `''` | one or two sentences: what it does and what it returns. Agents read it to choose the tool |
| `scope` | `''` | the scope a token needs, `resource:action` (`books:write`). `''`: any token |
| `level` | `0` | the minimum `permissions` of the user (signed in, or the owner of the token). `0`: anyone signed in |
| `readOnly` | `false` | it changes nothing: not audited when it succeeds; can be page data and a download; `readOnlyHint` for agents |
| `destructive` | `false` | it deletes or overwrites data: `destructiveHint`, agents ask the user first |
| `public` | `false` | anyone may call it, without signing in or a token |
| `mcp` | `true` | `false` keeps it out of MCP (a capability only a browser can use). REST still reaches it |
| `webOnly` | `false` | `true` (2.21.0): [`Route::action`](#webonly) reaches it, nothing else |
| `async` | `false` | `true` (2.23.0): a slow capability; [Snap](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant#tasks) runs it in the background as a Track card: Task. Other channels call it as before |

`php caligrafer.php service <Folder>/<Name> [--scope <scope>] [--read-only]` writes the class in
`application/services/<Folder>/<Name>.php`, the name in snake_case (`CreateBook` -> `create_book`). Without
`--scope` it writes `scope: ''` (G76). There is no `--destructive`: write `destructive: true` yourself.

### The class

| Part | Meaning |
| --- | --- |
| `public $rules` | input => [validation rules](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation). **Only these inputs reach `handle()`**: an input with no rule is listed with `''` |
| `public $filters` | input => filters applied before validation (`trim`) |
| `public $descriptions` | input => what it is, for the schema agents and clients see |
| `handle(array $input, Context $context)` | does the work and returns data: an array, a model, a list of models, a value (models become arrays of their columns) |
| `__construct(...)` | what it uses, given by the [container](https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection) |

A service does not render a view, redirect, print, or read the request or the session: the channel does that. A
web-only capability is the one exception, [below](#webonly).

`$this->capability($name, $input, $context)` (2.21.0) calls another capability as the same person, with its checks, its
validation and its audit, and throws its `ServiceError`.

### <a name="webonly"></a>Web-only capabilities

```php
#[Capability(name: 'open_author_books', description: 'Opens the books of an author.', readOnly: true, public: true, webOnly: true)]
```

For a request that belongs to the browser: a sign-in between two sites, a page that chooses where to go, a gate, a payment
page. A capability declared `webOnly: true` keeps its `public`, `scope` and `level` checks, its validation and its audit,
and may also return a `Caligrafy\Web` (`Web::view`, `Web::redirect`, `Web::json`, `Web::text`), read `session()` and
`request()`, sign people in, and change data on a `GET`. A JSON call to it needs the page's `X-CSRF-Token` or a token that grants `*`, signed in or not (2.21.1), and its route variables win over the query string (2.21.2). In exchange, **`Route::action` is the only way to it**: REST, MCP, the
JS client, `php caligrafer.php call`, `Route::page`, `Route::form` and a controller's `$this->call()` answer `not_found`, and it
is not listed in `GET /capabilities`, MCP or `php caligrafer.php capabilities`. A `service` command has no flag for it: add
`webOnly: true` to the attribute. Everything: [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#webonly).

**From the rules to the input schema** (what MCP and `GET /capabilities` show):

| Rule | Schema |
| --- | --- |
| `required` | listed in `required` |
| `integer` / `numeric`, `float` / `boolean` | `"type": "integer"` / `"number"` / `"boolean"` (otherwise `"string"`) |
| `valid_email`, `valid_url`, `uuid`, `date` | `"format": "email"`, `"uri"`, `"uuid"`, `"date"` |
| `max_len,N`, `min_len,N`, `exact_len,N` | `maxLength`, `minLength` |
| `min_numeric,N`, `max_numeric,N` | `minimum`, `maximum` (`current_year` is this year) |
| `contains_list,a;b` | `"enum": ["a", "b"]` |
| `file` | `"description": "The URL or the path of a file"` (web pages and REST upload the file: [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#files)) |

### Refusals: `ServiceError`

| Throw | Code | Status | When |
| --- | --- | --- | --- |
| `ServiceError::invalid(['field' => 'message'])` | `invalid` | 422 | an input is wrong |
| `ServiceError::unauthenticated()` | `unauthenticated` | 401 | nobody is signed in |
| `ServiceError::forbidden()` | `forbidden` | 403 | this caller may not do it (beyond the scope and level checks) |
| `ServiceError::notFound('There is no book #12')` | `not_found` | 404 | the thing does not exist |
| `ServiceError::conflict('This book is already lent to Ana')` | `conflict` | 409 | it clashes with the current state |

`$e->kind`, `$e->fields`, `$e->status()`, `$e->toArray()` (`{"error": {"code", "message", "fields"}}`).

### `Context`: who calls

| Member | Meaning |
| --- | --- |
| `$context->user` | the signed-in user, or the owner of the token (`null` otherwise) |
| `$context->token` | the token row (`id`, `name`, `scopes`, `user_id`...), or `null` |
| `$context->channel` | `web`, `rest`, `mcp` or `cli` |
| `$context->allows('books:write', 1)` | whether this caller has that scope and level |
| `$context->userId()`, `$context->level()` | the user's id, and `permissions` (0 without a user) |
| `$context->authenticated()` | anyone but a guest |
| `$context->actorType()`, `$context->actorId()` | who acts: `user`, `token`, `key`, `cli`, `guest`, or the system of a job or an event (`schedule`, `queue`, `webhook`), and its id. A capability only a webhook, the scheduler or the queue may run refuses every other `actorType()` |

**Scopes and levels** (`allows()`): the command line and the legacy key pass everything. A signed-in person needs
`permissions >= level` (no scopes). A token needs the scope (exact, `books:*` or `*`); when it has an owner
(`--user <id>`), the owner needs the level too. A token **without an owner** is limited by its scopes only: the level
does not apply to it, so give it destructive scopes with care (G53).

### Tokens

| Command | What it does |
| --- | --- |
| `php caligrafer.php token create "<name>" --scopes a:read,b:write [--user <id>] [--expires <days>]` | creates it and prints it once (`cq_<id>_<40 hex>`); only its SHA-256 hash is kept, in `caligrafy_tokens` |
| `php caligrafer.php token list` | `#<id> active/revoked/expired <name> <scopes> [user <id>] last used <when>/never used` |
| `php caligrafer.php token revoke <id>` | `Token #2 revoked`; the number alone (`revoke #2` revokes nothing, G77) |

A revoked, expired or unknown token is a visitor: `401`. From PHP: `Caligrafy\Tokens::create($name, $scopes, $userId,
time() + 86400 * 90)` returns `['id', 'token']`. An application online has no shell: give signed-in people a page
that creates their token (G79).

### MCP over HTTP

+ `POST` only, one JSON-RPC 2.0 message per request (no batches), answered in JSON: `initialize`, `ping`,
  `tools/list`, `tools/call`. A notification (no `id`) gets `202` and no body. `GET` and `DELETE` answer `405`.
+ Protocol versions `2025-11-25`, `2025-06-18`, `2025-03-26`, `2024-11-05` (another request gets the first).
+ Personal access tokens only: without one, `401` with `WWW-Authenticate: Bearer error="invalid_token"` and the
  JSON-RPC body `{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Unauthorized: send Authorization: Bearer
  <personal access token>"}}`, whatever the headers (2.19.1: before, a post with no token and no
  `Accept: application/json` was taken for a form and answered `403` `[ERROR 3000]`). The session is never used there.
+ A browser request from another site (`Origin` header) is refused with `403 Origin not allowed`. To allow a
  browser-based client, list its origin in `.env`: `MCP_ALLOWED_ORIGINS=https://inspector.example`.
+ A tool the token cannot see, or one that does not exist, answers `{"error": {"code": -32602, "message": "Unknown tool: create_book"}}`.

### Commands

| Command | What it does |
| --- | --- |
| `php caligrafer.php platform install` | the framework tables (tokens, audit, jobs, cache, migrations, notifications) |
| `php caligrafer.php capabilities [--json \| --markdown]` | the capabilities: a table, with the input schemas, or Markdown for your documentation |
| `php caligrafer.php call <name> ['{"key": "value"}' \| key=value ...] [--token <token>] [--guest]` | calls one, prints `{"data"}` or `{"error"}` (exit 1) |
| `php caligrafer.php client [<file>] [--prefix /capabilities]` | the JS client (default `public/js/capabilities.js`) |
| `php caligrafer.php mcp [--token <token>]` | MCP over stdio |
| `php caligrafer.php audit [--capability <name>] [--limit <n>]` | the latest calls, 50 by default |

All of them are on [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#service).
## Other ways

+ **A controller** [`Route::form`, `Route::page`, `Route::action`]: a controller you keep calls the capability as the
  signed-in person with `$this->call('create_book')`, the inputs being the posted fields and the route variables. New code
  does not need one: [Controllers](https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers) shows how to move it.
+ **A script** [`php caligrafer.php call`]: `Caligrafy\Capabilities::call('get_book', ['id' => 3], Caligrafy\Context::cli())`
  (with the checks and the audit), or `Caligrafy\Container::make(GetBook::class)->run(['id' => 3])` (validation only:
  no checks, no audit; it returns the model).
+ **The legacy API key** [tokens]: keys made with `generatekeys` and `generateapikey` all encrypt the same `APP_KEY`:
  each one gives full access, and none can be revoked without changing `APP_KEY`. They keep working for old programs
  (`Authorization: Bearer <key>` on REST, never on MCP). Once your programs use tokens, set `LEGACY_API_KEY=false` in
  `.env`; `doctor` reminds you while they are allowed. `Route::action` and controller routes accept JSON calls with a
  token that has the scope `*`. Never put a token or a key in a page or a Vue bundle: browser code uses the session.
## Common mistakes

+ **An input with no rule** (G52): it never reaches `handle()`. List it in `$rules`, with `''` when it has no rule.
+ **`service` without `--scope`** (G76): `scope: ''` lets any token call it.
+ **A write over the session without `X-CSRF-Token`** (G54): 403. Use the JS client, or send the `csrf` of `GET /capabilities`.
+ **A capability that is not read-only as page data** (G83): refused. Pages show read-only capabilities; forms use `Route::form`.
+ **`webOnly: true` on a feature agents or programs need** (G143): they get "There is no capability". Keep the work in a plain
  capability and let the web-only one call it with `$this->capability()`.
+ **Sending the legacy key to MCP** (G56): 401. MCP takes tokens only.
+ **Trusting the level with an application token** (G53): a token without `--user` passes any level. Create agent
  tokens with `--user <id>` when the level matters.
+ **Using `register_user` over REST or MCP** (G81): refused; sign-up is the sign-up page.
+ **Forgetting `php caligrafer.php client` after a change**: the Vue app calls the old functions.
## Related pages

+ [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability): the short tour
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes): `Route::form`, `Route::auth`, `Route::download`, `Route::webhook`
+ [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries) and [Relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships): reading data in `handle()`
+ [Validation](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation): the rules of `$rules`
+ [Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication): users, levels, tokens for agents
+ [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App), [Dependency injection](https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection), [Caching](https://github.com/caligrafy/caligrafy-quill/wiki/Caching)
+ [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer): every command

<br/><br/>
>[Next Section: Claude Code Plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Attribute -->

A **capability** is a class of `application/services/` that extends `Caligrafy\Service` and carries the attribute
`#[Capability(...)]`. The attribute says what the capability is called, what it does, who may call it and how the
channels treat it. This page lists every option; each one has a page of its own. Since 2.1.0 (`webOnly` 2.21.0,
`async` 2.23.0).

**Since 2.26.0**: `cache: <seconds>` (with `readOnly: true` and `public: true`: a visitor's answer may be kept by shared caches, see [performance](https://github.com/caligrafy/caligrafy-quill/wiki/Performance-and-Deployment)); and an empty `scope` on a write capability means a token needs the scope named after the capability, or `*`.
## With Claude

```text
/caligrafy-quill:new-capability delete_book books:write destructive: only administrators (level 1)
```

Claude runs `php caligrafer.php service <Folder>/<Name> --scope <scope>` and writes the attribute: a `description`
written for an AI agent, the scope, and `readOnly`, `destructive`, `level` or `public` from what you asked.

**Check** before you say OK: `php caligrafer.php capabilities` lists it with the scope (or `public`) and the flag you
expect (`read`, `writes`, `destroys`).
## By hand

`php caligrafer.php service Bookshelf/DeleteBook --scope books:write` writes the class with its name in snake_case
(`DeleteBook` becomes `delete_book`). Complete the attribute:

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;
use Caligrafy\ServiceError;

#[Capability(
    name: 'delete_book',
    description: 'Deletes a book of the catalog for good, with its loans and its tags. Returns the id of the deleted book.',
    scope: 'books:write',
    level: 1,
    destructive: true
)]
class DeleteBook extends Service
{
    public $rules = array('id' => 'required|integer');

    public $descriptions = array('id' => 'The id of the book to delete');

    public function handle(array $input, Context $context)
    {
        if (Book::where('id', $input['id'])->delete() === 0) {
            throw ServiceError::notFound('There is no book #' . $input['id']);
        }
        return array('deleted' => (int) $input['id']);
    }
}
```
## <a name="options"></a>Every option

The arguments of the attribute's constructor, in their order (`framework/core/Capability.php`):

| Option | Type, default | What it does | Learn more |
| --- | --- | --- | --- |
| `name` | `string`, required | snake_case: a letter, then letters, digits and `_`, 64 characters at most; unique in the application. How REST, MCP, the JS client, the command line and the routes name it. Any other name throws `InvalidArgumentException` | [Calling a capability from code](https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Call-a-Capability-from-Code) |
| `description` | `string`, `''` | one or two sentences: what it does and what it returns. Agents read it as the tool description | [MCP for AI agents](https://github.com/caligrafy/caligrafy-quill/wiki/MCP-for-AI-Agents) |
| `scope` | `string`, `''` | the token scope it needs, `resource:action` (`books:write`). `''`: any token | [Scopes and access](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Scopes-and-Access) |
| `level` | `int`, `0` | the minimum value of the users' `permissions` column. `0`: anyone signed in | [Scopes and access](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Scopes-and-Access#level) |
| `readOnly` | `bool`, `false` | it changes nothing: not audited when it succeeds, can be page data and a download, `readOnlyHint` for agents | [Read-only and destructive](https://github.com/caligrafy/caligrafy-quill/wiki/Read-Only-and-Destructive-Capabilities) |
| `destructive` | `bool`, `false` | it deletes or overwrites data: `destructiveHint`, agents ask the user first | [Read-only and destructive](https://github.com/caligrafy/caligrafy-quill/wiki/Read-Only-and-Destructive-Capabilities#destructive) |
| `public` | `bool`, `false` | anyone may call it, without signing in or a token | [Scopes and access](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Scopes-and-Access#public) |
| `mcp` | `bool`, `true` | `false` keeps it out of the MCP tools (one only a browser can use, such as a push subscription). REST still reaches it | [MCP for AI agents](https://github.com/caligrafy/caligrafy-quill/wiki/MCP-for-AI-Agents#mcpfalse) |
| `webOnly` | `bool`, `false` | `true` (2.21.0): only `Route::action()` reaches it; it may read the session and sign people in | [Web-only capabilities](https://github.com/caligrafy/caligrafy-quill/wiki/Web-Only-Capabilities) |
| `async` | `bool`, `false` | `true` (2.23.0): a slow capability; Snap runs it in the background as a Track card: Task. Other channels call it as before | [Async capabilities](https://github.com/caligrafy/caligrafy-quill/wiki/Async-Capabilities) |

The class itself declares the inputs (`$rules`, `$filters`, `$descriptions`) and `handle()`:
[Capability inputs](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Inputs). Its constructor gets what it
uses from the [container](https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection).

`php caligrafer.php service <Folder>/<Name> [--scope <scope>] [--read-only]` writes `scope` and `readOnly`. There is no
flag for `destructive`, `level`, `public`, `mcp`, `webOnly` or `async`: write them in the attribute.
## <a name="registry"></a>How the attribute is found

`Caligrafy\Capabilities::all()` builds the registry once per request: it loads the files of `application/services/`
that mention `#[Capability]` (with the class map, 2.18.0) and the framework's own capabilities of `framework/services/`,
then keeps every class that extends `Service`, is not abstract and carries the attribute. Two classes that declare the
same name stop the registry with a `LogicException` naming both. A class outside `application/services/` (a package, a
test) is added with `Capabilities::register(MyService::class)`.

Reference: [`Capability`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capability),
[`Capabilities::all()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capabilities-all),
[`Capabilities::register()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capabilities-register).
## Common mistakes

+ **`service` without `--scope`** (G76): it writes `scope: ''`, which any token may call. Give a scope, or write it in the
  attribute right away.
+ **`webOnly: true` on a feature agents or programs need** (G143): they get "There is no capability". Keep the work in a
  plain capability and let the web-only one call it with `$this->capability()`.
## Related pages

+ [Services, capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP): the whole chapter
+ [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability): the short tour
+ [Capability inputs](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Inputs) · [Refusing a call](https://github.com/caligrafy/caligrafy-quill/wiki/Refusing-a-Call-ServiceError) · [The context](https://github.com/caligrafy/caligrafy-quill/wiki/The-Context)
+ [API reference: services and capabilities](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Inputs -->

A capability declares its inputs with three arrays of its class: `$rules` (what is accepted), `$filters` (how it is
cleaned) and `$descriptions` (what each input is). The same three arrays validate every call, whatever the channel,
and become the **JSON Schema** that AI agents, the JS client and `GET /capabilities` see. Since 2.1.0.
## With Claude

```text
/caligrafy-quill:new-capability create_book books:write: add a book (title up to 200 characters, published year from 1450 to this year, optional summary, an existing author)
```

Claude writes a rule for every input, a `trim` filter for the text ones and a description for each, written for an
agent ("The id of its author (list_authors)").

**Check** before you say OK:
+ every input `handle()` reads is in `$rules` (with `''` when it has no rule);
+ `php caligrafer.php capabilities --json` shows the schema you expect;
+ `php caligrafer.php call <name>` with a wrong value answers a message for that field.
## By hand

```php
#[Capability(name: 'create_book', description: 'Adds a book to the Bookshelf catalog and returns it with its id and its author.', scope: 'books:write')]
class CreateBook extends Service
{
    public $rules = array(
        'title' => 'required|max_len,200',
        'published_year' => 'required|integer|min_numeric,1450|max_numeric,current_year',
        'summary' => 'max_len,2000',
        'author_id' => 'required|integer|exists,authors.id'
    );

    public $filters = array(
        'title' => 'trim',
        'summary' => 'trim'
    );

    public $descriptions = array(
        'title' => 'The title of the book',
        'published_year' => 'The year it was first published, for example 1969 (not after this year)',
        'summary' => 'Optional: one or two sentences about the book',
        'author_id' => 'The id of its author (list_authors)'
    );

    public function handle(array $input, Context $context)
    {
        $id = Book::insert($input);
        return Book::with('author')->find($id);
    }
}
```

`php caligrafer.php call create_book title=Dune` answers a message per field:
```json
{
    "error": {
        "code": "invalid",
        "message": "Some of the inputs are invalid",
        "fields": {
            "published_year": "The Published Year field is required",
            "author_id": "The Author Id field is required"
        }
    }
}
```
REST answers the same body with `422`, MCP as a tool result with `"isError": true`, a form goes back with
`errors('published_year')`.
## <a name="validate"></a>What happens to the inputs

`Service::validate()` runs before `handle()`, on every channel:

1. **Keep** only the inputs named in `$rules`. Any other key the caller sends is dropped: an input without a rule is
   listed with `''`.
2. **Files** (the `file` rule, 2.19.0): web pages and REST save the uploaded file and give the capability its public
   URL; MCP and the command line send a URL or a path, whose extension is checked. `required_file` (or
   `required|file`) with nothing sent is refused: "The Cover field needs a file".
3. **Numbers** (2.21.8): an input whose rule has `integer`, `numeric`, `float`, `min_numeric` or `max_numeric` never takes a
   list or `true`/`false`: "The Year field must be a number".
4. **Filter**, then **validate** with the [validation rules](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation)
   (GUMP). `$filters` apply only to declared inputs.
5. Anything wrong throws `ServiceError::invalid([field => message])`. Otherwise `handle()` gets the clean inputs.

`$rules` with `unique` and `exists` read the database (`exists,authors.id`); `current_year` in `min_numeric` and
`max_numeric` is the year of today.
## <a name="schema"></a>From the rules to the JSON Schema

`Capabilities::schema('create_book')` (and `schemaFromRules($rules, $descriptions)`) gives an object schema with
`"additionalProperties": false`:

| Rule | Schema |
| --- | --- |
| `required` | listed in `required` |
| `integer` / `numeric`, `float` / `boolean` | `"type": "integer"` / `"number"` / `"boolean"` (otherwise `"string"`) |
| `valid_email`, `valid_url`, `uuid`, `date` | `"format": "email"`, `"uri"`, `"uuid"`, `"date"` |
| `max_len,N`, `min_len,N`, `exact_len,N` | `maxLength`, `minLength` (both for `exact_len`) |
| `min_numeric,N`, `max_numeric,N` | `minimum`, `maximum` (`current_year` is this year) |
| `contains_list,a;b` | `"enum": ["a", "b"]` |
| `file`, `required_file` | `"description": "The URL or the path of a file"` (`required_file` also in `required`) |
| `$descriptions[input]` | `"description"`, over the one above |

A string keeps only its `format` and lengths, a number only its `minimum` and `maximum`. A rule argument that is not a
number (`max_len` with nothing after it) is left out of the schema. The `create_book` above becomes:

```json
{"type": "object", "properties": {
    "title": {"type": "string", "maxLength": 200, "description": "The title of the book"},
    "published_year": {"type": "integer", "minimum": 1450, "maximum": 2026, "description": "The year it was first published, for example 1969 (not after this year)"},
    "summary": {"type": "string", "maxLength": 2000, "description": "Optional: one or two sentences about the book"},
    "author_id": {"type": "integer", "description": "The id of its author (list_authors)"}},
 "additionalProperties": false, "required": ["title", "published_year", "author_id"]}
```

Reference: [`Service::validate()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#service-validate),
[`Capabilities::schema()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capabilities-schema),
[`Capabilities::schemaFromRules()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capabilities-schemafromrules),
[`Uploads`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#uploads).
## Common mistakes

+ **An input with no rule** (G52): it never reaches `handle()`. List it in `$rules`, with `''` when it has no rule.
+ **Forgetting `php caligrafer.php client` after changing the rules**: the Vue app's functions keep the old input types.
## Related pages

+ [Validation rules](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation): every rule and filter
+ [Declarative routes: file inputs](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#files)
+ [The capability attribute](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Attribute) · [Refusing a call](https://github.com/caligrafy/caligrafy-quill/wiki/Refusing-a-Call-ServiceError)
+ [MCP for AI agents](https://github.com/caligrafy/caligrafy-quill/wiki/MCP-for-AI-Agents): where agents read the schema


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/File-Uploads -->

# File uploads: the `file` rule

A capability declares a file input with the rule `file`, an optional allow-list of extensions and an optional maximum
size. Each channel then brings the file its own way, and `handle()` always gets a string: the file's public URL (web
pages, REST) or a URL or path (AI agents, the command line). Since 2.19.0; `required` with a file on every channel since
2.19.1.

```php
public $rules = array('cover' => 'required|file|extension,png;jpg;webp|max_size,2mb');
```
## With Claude

```text
/caligrafy-quill:new-capability set_cover books:write: sets the cover image of a book (PNG, JPG or WebP, 2 MB at most), from a form on the book's page
```

**Check** before you say OK:
+ the rule has `file`, an `extension` list and a `max_size`;
+ the form has `enctype='multipart/form-data'`;
+ a GIF, a 3 MB file and no file each come back with a message under the field.
## By hand

1. **A column for the file.** The table holds data: add it with a
   [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations):
   `docker compose exec dev-box php caligrafer.php migrate make add_books_cover`, then in the file it names:

   ```sql
   -- add_books_cover
   ALTER TABLE books ADD COLUMN cover VARCHAR(255) NULL AFTER summary;
   ```

   Run `docker compose exec dev-box php caligrafer.php migrate`.

2. **The capability.** `docker compose exec dev-box php caligrafer.php service Bookshelf/SetCover --scope books:write`,
   then make `application/services/Bookshelf/SetCover.php` read:

   ```php
   <?php

   use Caligrafy\Capability;
   use Caligrafy\Context;
   use Caligrafy\Database;
   use Caligrafy\Service;

   #[Capability(
       name: 'set_cover',
       description: 'Sets the cover image of a book, by its id. Returns the id and the URL of the cover.',
       scope: 'books:write'
   )]
   class SetCover extends Service
   {
       public $rules = array(
           'id' => 'required|integer|exists,books.id',
           'cover' => 'required|file|extension,png;jpg;webp|max_size,2mb',
       );

       public function handle(array $input, Context $context)
       {
           Database::table('books')->where('id', $input['id'])->update(array('cover' => $input['cover']));
           return array('id' => (int) $input['id'], 'cover' => $input['cover']);
       }
   }
   ```

3. **The route and the form.** In `web.php`:

   ```php
       Route::form('/books/{id}/cover', 'set_cover', ['success' => '/books/{id}', 'flash' => 'Cover saved']);
   ```

   On the book's page:

   ```pug
   form(method='POST', action=$home . 'books/' . $book['id'] . '/cover', enctype='multipart/form-data')
     =csrf()
     .cq-field
       label(for='cover') Cover (PNG, JPG or WebP, 2 MB at most)
       input#cover(type='file', name='cover', accept='.png,.jpg,.webp')
       if errors('cover')
         p.cq-field-error= errors('cover')
     button.btn.btn-secondary(type='submit') Save the cover
   ```

4. **Try it.** Choose a PNG and click **Save the cover**: "Cover saved", and the `cover` column holds
   `http://localhost:8080/public/uploads/<24 random characters>.png`. A GIF answers "This type of file is not accepted:
   png, jpg, webp"; a 3 MB PNG "The file is too large (at most 2 MB)"; no file "The Cover field needs a file".
## <a name="rules"></a>The rules

| Rule | What it does |
|---|---|
| `file` | the input is a file |
| `extension,png;jpg` | the types allowed; without it, the default list of `uploadFile()` applies (images, documents, audio, video, `zip`, `json`). Scripts and markup (`php`, `phtml`, `phar`, `html`, `js`, `svg`...) are always refused |
| `max_size,2mb` | a number of bytes, or `kb`, `mb`, `gb` (`500kb`, `1.5mb`). PHP's own limits (`upload_max_filesize`, `post_max_size`) apply first |
| `required` with `file`, or `required_file` | the file is required on every channel: no file, URL or path answers "The &lt;Field&gt; field needs a file", and the input schema of MCP and `GET /capabilities` lists the field in `required` (2.19.1) |

The file rules are never given to the validation library: `Service::validate()` takes them out and
`Caligrafy\Uploads` applies them.
## <a name="channels"></a>What each channel sends

| Channel | What `handle()` gets |
|---|---|
| Web pages (`Route::form`, `Route::action`) and REST (`Route::capability`, `Route::capabilities`) | the file is taken from the request once the caller is allowed to call the capability, checked (one file, the allow-list, the size), saved in `public/uploads/` under a new random name (the name the browser sent is never used), and `handle()` gets its public **URL**. A text sent in that field is dropped. When the capability fails, the saved file is deleted |
| AI agents (MCP) and the command line | they cannot send a file: they send a URL or a path, whose extension is checked against the allow-list. Never open it without checking where it points |
## Reference

+ [`Caligrafy\Uploads`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#uploads)
+ The helpers [`uploadFile()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-uploadfile),
  [`isAllowedUpload()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-isallowedupload) and
  [`deleteFile()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-deletefile)
## Common mistakes

+ **A file form without `enctype='multipart/form-data'`**: no file arrives, and the form comes back with "The Cover
  field needs a file".
+ **`required_file` alone on 2.19.0** was ignored; since 2.19.1 it makes the file required on every channel.
+ **Opening the path an agent sent** without checking where it points: the command line and MCP send a string, not an
  uploaded file.

## Related pages

+ [Forms: `Route::form`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Form)
+ [Validation](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation)
+ [Migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations)
+ [Declarative routes, step 7](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#files)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Scopes-and-Access -->

Three options of `#[Capability(...)]` say who may call a capability: `public`, `scope` and `level`. They are checked
once, in `Capabilities::call()`, for every channel: a page, a form, REST, the JS client, an agent over MCP, the command
line and the jobs all get the same answer. Since 2.1.0.

**Since 2.26.0** an empty `scope` on a write capability (not `readOnly`, not `public`) means a token needs the scope named after the capability (`create_book`) or `*`; `resource:*` does not cover it. Signed-in people and the command line are unchanged. `php caligrafer.php doctor` lists such capabilities; `TOKEN_DEFAULT_SCOPES=false` (deprecated) restores the old rule.
## With Claude

Say the scope and who may call it:

```text
/caligrafy-quill:new-capability list_books books:read read-only public: the catalog, 20 per page
/caligrafy-quill:new-capability delete_book books:write destructive: only administrators (level 1)
```

**Check** before you say OK:
+ `php caligrafer.php capabilities` shows `public`, the scope, or `signed in` (no scope) in the second column;
+ `php caligrafer.php call <name> --guest` answers `unauthenticated` for a capability that is not public;
+ a token without the scope gets `403` over REST and does not see the tool in MCP `tools/list`.
## By hand

```php
#[Capability(name: 'list_books', description: 'Lists the books of the catalog, 20 per page.', readOnly: true, public: true)]
#[Capability(name: 'create_book', description: 'Adds a book to the catalog and returns it.', scope: 'books:write')]
#[Capability(name: 'delete_book', description: 'Deletes a book for good. Returns its id.', scope: 'books:write', level: 1, destructive: true)]
```

(one attribute per class). Then try each caller:

```bash
php caligrafer.php call create_book title=Dawn published_year=1987 author_id=2 --guest          # unauthenticated
php caligrafer.php token create "Reader" --scopes books:read
php caligrafer.php call create_book title=Dawn published_year=1987 author_id=2 --token cq_...   # forbidden
```

The second call answers `{"error":{"code":"forbidden","message":"This needs the scope books:write"}}`; with a `level`
the message ends with `and permission level 1`.
## <a name="order"></a>The checks, in order

`Capabilities::call()`:

1. **Find** it: no such name, or a `webOnly` capability reached by anything but `Route::action`, is `not_found`.
2. **`public: true`**: no check at all; anyone may call it, visitors included.
3. **Someone must act**: a guest (nobody signed in, no token) is `unauthenticated` (401).
4. **`$context->allows($scope, $level)`**, else `forbidden` (403).
5. Then the inputs are validated and `handle()` runs. A capability can still refuse more itself, with
   `ServiceError::forbidden()` ([Refusing a call](https://github.com/caligrafy/caligrafy-quill/wiki/Refusing-a-Call-ServiceError)).
## <a name="scope"></a>`scope`: what a token may do

A scope is `<resource>:<action>`: lowercase letters, digits, `_`, `.` and `-` on each side (`books:read`,
`books:write`). The scopes a token was given cover a required scope when one of them is:

+ the same scope (`books:write`);
+ `<resource>:*` (`books:*` covers `books:read` and `books:write`);
+ `*` (everything).

`scope: ''` is met by **any** token. Scopes apply to tokens only: a signed-in person has every scope, and is checked by
the level.
## <a name="level"></a>`level`: how much a person may do

`level` is the minimum value of the users' `permissions` column (`Context::$levelAttribute`, `permissions` by default).
`0`, the default, means anyone signed in. `$context->level()` is the user's value, `0` without a user.

| Caller | What `allows($scope, $level)` checks |
| --- | --- |
| the command line, scripts and jobs (`Context::cli()`, `Context::system()`), the legacy API key | nothing: always allowed |
| a signed-in person | `permissions >= level` |
| a token with an owner (`token create ... --user 7`) | the scope, and the owner's `permissions >= level` |
| a token without an owner | the scope only: the level does not apply |
| a token whose owner was deleted (with authentication on) | refused |
| a guest | refused (only public capabilities) |
## <a name="public"></a>`public`: anyone

`public: true` skips the checks: a visitor's page, a REST call without a token and any MCP token reach it. Use it for
what anyone may read (the catalog), or for what a visitor must do before having an account. A public capability may still
look at `$context` and refuse: the framework's `register_user` is public but refuses every channel but web pages and the
command line (G81).
## <a name="lists"></a>What each caller sees

`Capabilities::available($context)` keeps the capabilities this caller may call (public, or allowed), web-only ones left
out. MCP `tools/list` and `GET /capabilities` show only those, so a token never sees a tool it may not call.

Reference: [`Context::allows()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#context-allows),
[`Tokens::allows()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#tokens-allows),
[`Capabilities::available()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capabilities-available).
## Common mistakes

+ **`service` without `--scope`** (G76): `scope: ''` lets any token call it.
+ **Trusting the level with an application token** (G53): a token without `--user` passes any level. Create agent tokens
  with `--user <id>` when the level matters.
+ **The legacy API key and tokens without an owner never manage users** (G85): the user capabilities need a real
  administrator, so give an agent that manages users a token of an administrator.
## Related pages

+ [Personal access tokens](https://github.com/caligrafy/caligrafy-quill/wiki/Personal-Access-Tokens) · [The context](https://github.com/caligrafy/caligrafy-quill/wiki/The-Context)
+ [Authentication: users and levels](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication)
+ [The capability attribute](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Attribute)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Read-Only-and-Destructive-Capabilities -->

Two options of `#[Capability(...)]` say what a capability does to the data: `readOnly: true` (it changes nothing) and
`destructive: true` (it deletes or overwrites). They are promises the channels act on: where a capability may be used,
what is audited, and whether an agent or the assistant asks the person first. A capability with neither **writes**.
Since 2.1.0.
## With Claude

```text
/caligrafy-quill:new-capability list_books books:read read-only public: the catalog, 20 per page
/caligrafy-quill:new-capability delete_book books:write destructive: only administrators (level 1)
```

**Check** before you say OK: `php caligrafer.php capabilities` shows `read`, `writes` or `destroys` in the third column,
as you expect.
## By hand

`php caligrafer.php service Bookshelf/ListBooks --scope books:read --read-only` writes `readOnly: true`. There is no flag
for `destructive`: add it to the attribute.

```php
#[Capability(name: 'list_books', description: 'Lists the books of the catalog, sorted by title, 20 per page.', scope: 'books:read', readOnly: true)]
#[Capability(name: 'delete_book', description: 'Deletes a book of the catalog for good, with its loans and its tags. Returns the id of the deleted book.', scope: 'books:write', level: 1, destructive: true)]
```

(one attribute per class). Declare only what is true: `readOnly` on a capability that writes would let a page or a link
change data without a trace in the audit log.
## <a name="readonly"></a>What `readOnly: true` changes

| Where | A read-only capability | Any other |
| --- | --- | --- |
| The audit log | written only when it is refused | every call: success and refusal |
| `Route::page(..., ['data' => [...]])` | can be page data | refused: `LogicException` "changes data, and opening a page must not" |
| `Route::download` | can be downloaded | refused: `LogicException` "changes data, and opening a link must not" |
| REST with the session cookie | no CSRF token needed | needs `X-CSRF-Token` (403 without it) |
| REST `POST` | `200` | `201` |
| MCP | `"readOnlyHint": true` | `"readOnlyHint": false` |
| Snap | a card with nothing to ask runs at once; the assistant may call it to look things up | comes back as an Ask: Confirm card first |
## <a name="destructive"></a>What `destructive: true` changes

+ **MCP**: `"destructiveHint": true` on the tool (only when it is not also read-only), and the server's `initialize`
  instructions tell the agent: "Tools marked destructive delete or overwrite data: confirm with the user first."
+ **`php caligrafer.php capabilities`**: `destroys` instead of `writes`; `GET /capabilities` and `--json` give
  `"destructive": true`.
+ **The JS client**: the function's comment says `destructive`.
+ **Snap**: the card is a `destroy` risk (a `write` one without it); like every change, it runs only once the person has
  confirmed its Ask: Confirm card.

Nothing else differs: the checks, the validation and the audit are those of every capability that writes.
## <a name="snap"></a>Snap and the assistant

In [Snap](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant), nothing that changes data runs
from a card until the person confirms it: a capability that is not read-only answers an **Ask: Confirm** card with a
one-time token bound to that person, that capability and those inputs, for 10 minutes. The confirmed change is written to
the audit log as `snap_confirm`. The assistant (Claude) may call only the read-only capabilities the person may call, to
look things up; a change it proposes comes back as its Confirm card. A slow read-only capability declared
[`async: true`](https://github.com/caligrafy/caligrafy-quill/wiki/Async-Capabilities) is proposed as a task instead of
being run in the turn.

Reference: [`Capabilities::call()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capabilities-call),
[`Mcp\Server::tools()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#mcp-server-tools),
[`Snap\Consent`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-consent).
## Common mistakes

+ **A capability that is not read-only as page data** (G83): refused. Pages show read-only capabilities; forms use
  `Route::form`.
## Related pages

+ [The capability attribute](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Attribute) · [The audit log](https://github.com/caligrafy/caligrafy-quill/wiki/The-Audit-Log)
+ [MCP for AI agents](https://github.com/caligrafy/caligrafy-quill/wiki/MCP-for-AI-Agents) · [REST API](https://github.com/caligrafy/caligrafy-quill/wiki/REST-API)
+ [Declarative routes: downloads](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#download)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Web-Only-Capabilities -->

A **web-only capability** is a capability declared `webOnly: true`. It is for a request that belongs to the browser: a
sign-in between two sites, a page that chooses between a view and a redirect, a gate, a page that creates a payment.
It keeps everything a capability has (its checks, its validation, its audit) and may do what a plain capability never
does: answer with a view or a redirect, read the session, sign people in. The price: `Route::action` is the only way to
it. Since 2.21.0.

This page is about the capability. The route that serves it, its options and how it answers are on
[`Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Action).
## With Claude

```text
/caligrafy-quill:new-capability open_author_books web-only public: open the books of an author, the book itself when there is only one
```

Claude writes the capability with `webOnly: true`, keeps the shared work in plain capabilities that it calls with
`$this->capability()`, and adds the `Route::action` line to `web.php`.

**Check** before you say OK:
+ `php caligrafer.php capabilities` does not list it (web-only capabilities are left out);
+ the plain capabilities it calls are listed, so agents and programs can still do the work;
+ a test calls it with `$this->action()`.
## By hand

`php caligrafer.php service Bookshelf/OpenAuthorBooks` writes the class; the command has no flag for web-only, so add
`webOnly: true` to the attribute:

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;
use Caligrafy\Web;

#[Capability(
    name: 'open_author_books',
    description: 'Opens the books of an author: the book itself when there is one, otherwise the list.',
    readOnly: true,
    public: true,
    webOnly: true
)]
class OpenAuthorBooks extends Service
{
    public $rules = array('author_id' => 'required|integer');

    public function handle(array $input, Context $context)
    {
        $books = $this->capability('list_books', array('author_id' => $input['author_id']), $context);
        if ($books['total'] == 1) {
            return Web::redirect('/books/' . $books['data'][0]['id']);
        }
        return Web::view('Bookshelf/books', array('books' => $books));
    }
}
```

and serve it in `application/config/routing/web.php`, before `Route::run();`:

```php
Route::action('/authors/{author_id}/books', 'open_author_books', ['back' => '/books']);
```
## <a name="may"></a>What it may do

The rule of the framework still holds: **only capabilities touch models**. A web-only capability is a capability; what
sets it apart is what it may do besides:

| A plain capability | A web-only capability |
|---|---|
| returns data, or refuses | may also return a view, a redirect, JSON or text (`Caligrafy\Web`) |
| never reads the session or the request: `$context` says who calls | may read `session()`, `request()`, `$_SERVER`, `$_COOKIE` |
| never signs anyone in | may sign people in and out |
| on a page, only `readOnly` | a `GET` may change data |
| reached by REST, MCP, the JS client, the command line, `Route::page`, `Route::form`, `$this->call()` | reached by **`Route::action` only** |

What it answers:

| It returns | The browser gets |
|---|---|
| `Web::view('Bookshelf/book', $data, $status = 200)` | a Pug view, with `$authorized` and `$user` as on `Route::page` |
| `Web::redirect('/books', $status = 302)` | a redirect: a path of this site or a full `http(s)` address |
| `Web::json($data, $status = 200)` | JSON, the data as it is |
| `Web::text($body, $status = 200)` | the text as it is |
| any of them `->header('Cache-Control', 'no-store')` | one more response header |
| plain data | JSON |
## <a name="elsewhere"></a>Everywhere else: "There is no capability"

`Capabilities::call()` answers `not_found` `There is no capability '<name>'` to any context that does not come from
`Route::action` (`$context->viaAction`). So REST, MCP, the JS client, `php caligrafer.php call`, `Route::page`,
`Route::form`, `Route::download` and a controller's `$this->call()` cannot reach it, and it is left out of
`GET /capabilities`, MCP `tools/list`, `php caligrafer.php capabilities` and the generated JS client.

Keep the work several channels share in plain capabilities, and call them from the web-only one, as the same person:

```php
$books = $this->capability('list_books', array('author_id' => 2), $context);   // its checks, validation and audit
```
## <a name="signin"></a>Signing someone in

+ For a page that leaves or reloads: `Caligrafy\AuthRoutes::signIn($user, null, 'partner')`: a new session id, a new CSRF
  token and how it signed in (the third argument, 2.21.3, read by `AuthRoutes::signedInBy()`).
+ For a page that stays open and keeps sending JSON: `session_regenerate_id(true); Auth::authorize($user);
  AuthRoutes::rememberSignIn('face');`: the page keeps its token.
+ `$context` was built before the sign-in and does not change: to call a capability as the person just signed in, build a
  new one with `Context::fromRequest(request(), 'web')`.

A whole example, a sign-in through another site, is on
[Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#betweensites).
## <a name="test"></a>Testing

`$this->action('open_author_books', ['author_id' => 3], $user)` calls it as `Route::action` does and returns what it
answered; `->describe()` gives `type`, `target`, `data`, `status` and `headers`. `$this->call()` answers `not_found`, as
every other channel does ([Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App#helpers)).

Reference: [`Caligrafy\Web`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#web),
[`Caligrafy\Action`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#action),
[`AuthRoutes::signIn()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AuthRoutes#authroutes-signin).
## Common mistakes

+ **`webOnly: true` on a feature agents or programs need** (G143): they get "There is no capability". Keep the work in a
  plain capability and let the web-only one call it with `$this->capability()`.
+ **Reading the session in a plain capability** (G52): only a web-only capability may; the others read `$context`.
+ **Snap's own `snap_ask` and `snap_run` in a test** (G158): they are web-only, so call them with `$this->action()`.
## Related pages

+ [`Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Action): the route, its options, CSRF and JSON
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#webonly)
+ [The capability attribute](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Attribute) · [The context](https://github.com/caligrafy/caligrafy-quill/wiki/The-Context)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Async-Capabilities -->

A capability declared `async: true` is **slow**: a report, a long count, an AI call. In
[Snap](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant) it never runs in the request:
the person gets a **Track card: Task** at once, a job of the [queue](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs)
runs it as that person, and they are notified when it ends. Every other channel (pages, REST, MCP, the command line)
still calls it directly, as before. Since 2.23.0.
## With Claude

```text
/caligrafy-quill:new-capability reading_report books:read read-only async: the books read this year by every reader, by month
```

Claude writes the capability with `async: true` and makes sure a worker runs the queue (a job on `queue_work` in
`application/config/schedule.php`).

**Check** before you say OK:
+ in Snap, asking for it shows a Task card that goes from *Waiting to start* to *Working on it*, then its result;
+ `php caligrafer.php queue work --once` runs the waiting `snap_task_run` job.
## By hand

1. **The tables.** `docker compose exec dev-box php caligrafer.php platform install` creates the queue's `caligrafy_jobs`
   and Snap's tables (the deploy step does too).
2. **Declare it.**
    ```php
    #[Capability(name: 'reading_report', description: '...', scope: 'books:read', readOnly: true, async: true)]
    ```
    Or leave the attribute as it is and make it async for Snap only, with the hint `async` in `application/config/snap.php`;
    `working` gives the lines the card shows, in turn, while it runs:
    ```php
    return [
        'cards' => [
            'reading_report' => ['async' => true, 'working' => ['Counting the books…']],
        ],
    ];
    ```
3. **A worker.** Something must run the queue: a job on `queue_work` in `application/config/schedule.php`
   (`array('name' => 'queue', 'capability' => 'queue_work', 'every' => '1m', 'timeout' => 55)`, which Caligrafy Cloud and
   `server start` run), or `php caligrafer.php queue work` on your own server. See
   [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs).
## <a name="run"></a>How a task runs

1. A read starts as a task at once; a change starts after the person confirms its Ask: Confirm card. Only a signed-in
   person can start one (a visitor gets `unauthenticated`).
2. `Snap\Tasks::start()` writes a row of `caligrafy_snap_tasks` (the person, the capability, the inputs, `queued`) and
   pushes the job `snap_task_run` to the queue, with 3 attempts and a 120 second timeout.
3. The worker runs the capability with `Capabilities::call()` **as the person who asked**: their user on the `web`
   channel, so their permissions, not the queue's full access. Its checks, validation and audit are those of any call.
4. It ends in one of three states, keeps the card it ended with, and notifies the person on every channel they turned on
   ([Notifications](https://github.com/caligrafy/caligrafy-quill/wiki/Notifications)):

| Status | Label | When | The card it ends with |
| --- | --- | --- | --- |
| `queued` | Waiting to start | pushed, or put back for the queue's next attempt after an error | |
| `running` | Working on it | the worker started it | |
| `done` | Done | it answered | the Show card of the result |
| `needs_input` | Needs your answer | it refused an input (`invalid`) | the Ask card of what it refused; answering it starts a new task |
| `failed` | Could not finish | it refused (`forbidden`, `unauthenticated`, `not_found`, `conflict`), the person no longer exists, or the queue's retries ran out | a notice |

The Track card shows where it is, live, with its steps (Asked, Started, then how it ended); Home shows it in progress,
then just done. A person sees only their own tasks.

Reference: [`Snap\Tasks`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-tasks),
[`Snap\Tasks::async()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-tasks-async),
[`Queue::push()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Jobs#queue-push).
## <a name="channels"></a>On the other channels

`async` changes nothing outside Snap: REST, MCP, the JS client, `Route::page`, `Route::form` and
`php caligrafer.php call` run it in the request, as any capability. To run any capability later from your own code,
push it to the queue yourself: `Queue::push('build_report', ['month' => '2026-11'])`
([Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs)).
## Related pages

+ [Snap Cards and the assistant: work in the background](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant#tasks)
+ [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs) · [Scheduled jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs)
+ [The capability attribute](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Attribute)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Refusing-a-Call-ServiceError -->

A capability refuses a call by throwing a `Caligrafy\ServiceError`. It never prints an error, redirects or picks an
HTTP status itself: each channel turns the same refusal into its own form, a status and a JSON error for REST, a tool
error for an agent, the errors of a form for a page. Since 2.1.0.
## With Claude

Say when the capability must refuse:

```text
/caligrafy-quill:new-capability lend_book loans:write: lend a book to a reader; refuse when the book is already out
```

Claude throws `ServiceError::notFound()` for a book that does not exist and `ServiceError::conflict()` when it is lent.

**Check** before you say OK: `php caligrafer.php call <name> ...` with the case that must be refused prints
`{"error": {"code": ...}}` with the code you expect, and exits with 1.
## By hand

```php
use Caligrafy\ServiceError;

public function handle(array $input, Context $context)
{
    $book = Book::find($input['book_id']);
    if (!$book) {
        throw ServiceError::notFound('There is no book #' . $input['book_id']);
    }
    if (Loan::where('book_id', $input['book_id'])->whereNull('returned_at')->exists()) {
        throw ServiceError::conflict('This book is already lent');
    }
    // ...
}
```

The invalid inputs of `$rules` are refused before `handle()` runs, with a message per field: you throw `invalid` only
for what the rules cannot say.

```php
throw ServiceError::invalid(['due_at' => 'The due date must be after today']);
```
## <a name="kinds"></a>The five kinds

| Throw | Code | Status | Default message | When |
| --- | --- | --- | --- | --- |
| `ServiceError::invalid(['field' => 'message'], $message)` | `invalid` | 422 | Some of the inputs are invalid | an input is wrong |
| `ServiceError::unauthenticated($message)` | `unauthenticated` | 401 | Sign in or send a personal access token | nobody is signed in |
| `ServiceError::forbidden($message)` | `forbidden` | 403 | You are not allowed to do this | this caller may not do it |
| `ServiceError::notFound($message)` | `not_found` | 404 | Not found | the thing does not exist |
| `ServiceError::conflict($message)` | `conflict` | 409 | (a message is required) | it clashes with the current state |

`new ServiceError($kind, $message = '', $fields = [])` does the same; any other kind throws `InvalidArgumentException`.
On the error: `$e->kind`, `$e->fields`, `$e->getMessage()`, `$e->status()` and `$e->toArray()`, which is
`{"error": {"code": "invalid", "message": "...", "fields": {...}}}` (`fields` only when there are some).

The framework throws the same errors itself: `not_found` for an unknown capability, `unauthenticated` and `forbidden`
("This needs the scope books:write") from the [access checks](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Scopes-and-Access),
`invalid` from the [input rules](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Inputs).
## <a name="channels"></a>What each channel makes of it

| Channel | What the caller gets |
| --- | --- |
| REST (`Route::capability`, `Route::capabilities`) | the status of the kind and `$e->toArray()` as JSON; `401` also sends `WWW-Authenticate: Bearer` |
| MCP | a tool result with `"isError": true` and `$e->toArray()` as its text, so the agent can read the reason and correct itself |
| `php caligrafer.php call` | `$e->toArray()` as JSON, exit code `1` |
| The JS client | a `CapabilityError` with `status`, `code`, `message` and `fields` |
| `Route::form`, `Route::action` (a browser) | `invalid` or `conflict`: back, with `errors()`, `old()`, `flash('error')`; `unauthenticated`: the sign-in page; `forbidden`: `403` `[ERROR 1006]`; `not_found` or anything else: `404` `[ERROR 1005]` |
| `Route::form`, `Route::action` (a JSON request) | the status of the kind and the REST error |
| `Route::page` data | a visitor goes to sign in (with the authentication module), otherwise `403` or `404`; with `'notFound' => 'Folder/view'` that view, its `$message` the refusal |
| Snap | an Ask card for `invalid` (the fields to fix), a notice for the others |

Every refusal is written to the [audit log](https://github.com/caligrafy/caligrafy-quill/wiki/The-Audit-Log), its outcome
the code and its detail the message. Any other exception is written with the outcome `error` and the exception's class,
then thrown on: it is a bug, not a refusal.

Reference: [`ServiceError`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#serviceerror),
[`Capabilities::call()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capabilities-call).
## Related pages

+ [Declarative routes: forms](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form): `errors()`, `old()` and `flash()` in the view
+ [REST API](https://github.com/caligrafy/caligrafy-quill/wiki/REST-API) · [MCP for AI agents](https://github.com/caligrafy/caligrafy-quill/wiki/MCP-for-AI-Agents) · [The JS client](https://github.com/caligrafy/caligrafy-quill/wiki/The-JS-Client)
+ [The context](https://github.com/caligrafy/caligrafy-quill/wiki/The-Context): who calls, to decide what to refuse


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/The-Context -->

Every capability gets a `Caligrafy\Context` as the second argument of `handle()`. It says **who calls, through which
channel, with which rights**: a signed-in person, a token, the command line, a job or a visitor. The channels build it
(a page, REST, MCP, the command line); a capability reads it instead of the request, the session or the headers, so the
same code works for every caller. Since 2.1.0.
## With Claude

Say what depends on the caller:

```text
/caligrafy-quill:new-capability my_loans loans:read read-only: the loans of the person who asks, newest first
```

Claude reads `$context->userId()` in `handle()`, and refuses with `ServiceError::unauthenticated()` when there is none.

**Check** before you say OK: `php caligrafer.php call my_loans --guest` is refused, and two people each see only their own
rows.
## By hand

```php
#[Capability(name: 'my_loans', description: 'Lists the loans of the person who asks, newest first.', scope: 'loans:read', readOnly: true)]
class MyLoans extends Service
{
    public function handle(array $input, Context $context)
    {
        if (!$context->userId()) {
            throw ServiceError::unauthenticated();
        }
        return Loan::where('user_id', $context->userId())->latest()->get();
    }
}
```

A capability only a job may run (it works with full access) refuses everyone else by the actor type:

```php
if (!in_array($context->actorType(), array('queue', 'cli'), true)) {
    throw ServiceError::forbidden();
}
```
## <a name="members"></a>What it holds

| Member | Meaning |
| --- | --- |
| `$context->channel` | `web`, `rest`, `mcp` or `cli` |
| `$context->user` | the user model: signed in, or the owner of the token (`null` otherwise) |
| `$context->token` | the token row (`id`, `name`, `scopes`, `user_id`...), or `null` |
| `$context->viaAction` | `true` when the call comes from `Route::action` (2.21.0): the only way to a [web-only capability](https://github.com/caligrafy/caligrafy-quill/wiki/Web-Only-Capabilities) |
| `$context->authenticated()` | anyone but a guest |
| `$context->allows('books:write', 1)` | whether this caller has that scope and level ([Scopes and access](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Scopes-and-Access)) |
| `$context->userId()` | the user's id, signed in or owner of the token |
| `$context->level()` | the user's `permissions` column (`Context::$levelAttribute`), `0` without a user |
| `$context->actorType()` | `user`, `token`, `key`, `cli`, `guest`, or the system of a job or an event (`schedule`, `queue`, `webhook`), as written to the audit log |
| `$context->actorId()` | the token id or the user id as a string, or the job's name; `null` for the command line, the legacy key and guests |
## <a name="who"></a>Who the channels say calls

| Caller | How the context is made | Rights |
| --- | --- | --- |
| a request with `Authorization: Bearer cq_...` | `Context::fromRequest($request, $channel)`: the token, and its owner when it has one and authentication is on | the token's scopes (an unknown, revoked or expired token is a guest) |
| a request with the legacy API key | `fromRequest`: a full-access context | everything (actor `key`) |
| a signed-in person (the session) | `fromRequest`: the user | their level |
| nobody | `Context::guest($channel)` | public capabilities only |
| the command line and scripts | `Context::cli()` | everything (actor `cli`) |
| `php caligrafer.php mcp` without a token | `Context::local('mcp')` | everything (actor `cli`) |
| a scheduled job or another system task | `Context::system('schedule', $jobName)` | everything; the audit log records the type and the name |
| a personal access token in code | `Context::forToken($tokenRow, $channel)` | the token's scopes |

`fromRequest()` looks in that order: a token, then the legacy key, then the session, else a guest. The context is made
once, before the capability runs: when a [web-only capability](https://github.com/caligrafy/caligrafy-quill/wiki/Web-Only-Capabilities#signin)
signs someone in, it builds a new one with `Context::fromRequest(request(), 'web')` to call as that person.

Reference: [`Caligrafy\Context`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#context).
## Common mistakes

+ **Reading the session or the request in a capability** (G52): the channel does that, and `$context` says who calls. Only a
  web-only capability may.
+ **A job capability that anyone may call**: it runs with full access, so check `actorType()`
  ([Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs)).
+ **Trusting the level with an application token** (G53): a token without an owner passes any level.
## Related pages

+ [Scopes and access](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Scopes-and-Access) · [Personal access tokens](https://github.com/caligrafy/caligrafy-quill/wiki/Personal-Access-Tokens)
+ [Calling a capability from code](https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Call-a-Capability-from-Code)
+ [The audit log](https://github.com/caligrafy/caligrafy-quill/wiki/The-Audit-Log)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Personal-Access-Tokens -->

A program or an AI agent proves who it is with a **personal access token**: `cq_<id>_<40 hexadecimal characters>`,
sent as `Authorization: Bearer cq_...`. A token has a name, **scopes** (what it may do), and optionally an owner (the
user it acts for) and an expiry. It is shown once, only its SHA-256 hash is kept, and it can be revoked on its own.
REST, MCP, the JS client outside the browser and `php caligrafer.php call --token` all take it. Since 2.1.0.

**Since 2.26.0** a capability's name is a valid scope (`php caligrafer.php token create ci --scopes create_book`): a write capability declared without a `scope` needs it, or `*`.
## With Claude

```text
Create a token for my Claude Code on this laptop that can read and write books, for 90 days
```

Claude runs `php caligrafer.php token create` with the scopes, shows the token once, and never writes it in a file.

**Check** before you say OK: `php caligrafer.php token list` shows it `active` with the scopes you asked for.
## By hand

1. **The framework tables.** `docker compose exec dev-box php caligrafer.php platform install` creates
   `caligrafy_tokens` (and the other framework tables; safe to run again).
2. **Create it.**
    ```bash
    docker compose exec dev-box php caligrafer.php token create "Bookshelf agent" --scopes books:read,books:write
    ```
    ```text
     Token #1 "Bookshelf agent" created with books:read books:write

     cq_1_<40 hexadecimal characters>

     It is shown only now: store it as a secret (Authorization: Bearer <token>).
    ```
3. **Use it.**
    ```bash
    curl -s -H "Authorization: Bearer cq_1_..." http://localhost:8080/api/books
    ```
4. **List and revoke.**
    ```bash
    docker compose exec dev-box php caligrafer.php token list
    docker compose exec dev-box php caligrafer.php token revoke 1
    ```
    ```text
     #1    active   Bookshelf agent                books:read books:write  never used
    ```
## <a name="command"></a>The `token` command

```text
 php caligrafer.php token create <name> --scopes <a:read,b:write | *> [--user <id>] [--expires <days>]
 php caligrafer.php token list
 php caligrafer.php token revoke <id>
```

+ `--scopes` (required): `resource:action` values separated by commas; `books:*` for every action on books; `*` for everything.
+ `--user <id>`: the token acts for that user, so a capability's `level` applies to them.
+ `--expires <days>`: the token stops working after that many days.
+ `token list` shows `#<id>`, `active`, `revoked` or `expired`, the name, the scopes, the owner and the last use, never the
  secret. `token revoke` takes the number alone and stops the token at once.
## <a name="scopes"></a>Scopes

A scope is `<resource>:<action>` in lowercase (`books:read`, `loans:write`). A capability declares the one it needs with
`scope: 'books:write'`; a token reaches it when it has that scope, `books:*`, or `*`. A capability with `scope: ''` is
reached by any token. A token with an owner also needs the owner's level; a token **without** an owner is limited by its
scopes only. All the rules: [Scopes and access](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Scopes-and-Access).

A revoked, expired or unknown token is a visitor: `401` on REST and MCP. A token whose owner was deleted is refused.
## <a name="php"></a>From PHP

```php
use Caligrafy\Tokens;

$created = Tokens::create('Sam\'s agent', ['books:read', 'books:write'], $userId, time() + 86400 * 90);
// ['id' => 3, 'token' => 'cq_3_...']: the token is never shown again

Tokens::revoke(3);       // true when a token was revoked
Tokens::all();           // the rows, newest first, without their secret
```

`Tokens::verify('cq_...')` returns the token row (its scopes as a list) and records its use, or `null`. The expiry is a
Unix time (or a local `'Y-m-d H:i:s'`, stored as given); a Unix time is stored so that the token never stops early when
the clocks fall back.
## <a name="online"></a>Tokens for an application online

An application on Caligrafy Cloud or your own server has no shell for `token create`. Give signed-in people a page that
creates their own token: a capability that calls `Tokens::create($name, $scopes, $context->user->id, $expiresAt)`, refuses
when `$context->token !== null` (a token must not create tokens), and a page that shows the token once with the
`claude mcp add` line.

Reference: [`Caligrafy\Tokens`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#tokens),
[`Tokens::create()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#tokens-create).
## Common mistakes

+ **`token revoke #2`** (G77): it reads `#2` as 0 and revokes nothing. Use `token revoke 2`.
+ **No page to create tokens online** (G79): agents cannot connect to a deployed application without one.
+ **An expiry as a date string near a clock change** (G91): give it as a Unix time (`time() + 86400 * 90`).
+ **Trusting the level with an application token** (G53): create agent tokens with `--user <id>` when the level matters.
+ **A token or a key in a page or a Vue bundle**: browser code uses the session; tokens are for programs and agents.
## Related pages

+ [MCP for AI agents](https://github.com/caligrafy/caligrafy-quill/wiki/MCP-for-AI-Agents) · [REST API](https://github.com/caligrafy/caligrafy-quill/wiki/REST-API)
+ [Authentication: users, tokens and agents](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#agents)
+ [Caligrafer: `token`](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#token)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/The-Audit-Log -->

The **audit log** keeps one row per capability call that changes data, and per refused call: when, through which
channel, who (a person, a token, the command line, a job), which capability and the outcome. Inputs are never stored.
It is written by `Capabilities::call()`, so every channel is in it: pages, forms, REST, the JS client, MCP, the command
line, the queue and the scheduler. Since 2.1.0.
## By hand

1. **The table.** `docker compose exec dev-box php caligrafer.php platform install` creates `caligrafy_audit`. Without it
   nothing is written and nothing fails.
2. **Read it.**
    ```bash
    docker compose exec dev-box php caligrafer.php audit --capability create_book --limit 5
    ```
    ```text
     2026-11-07 23:18:39  mcp   token  1            create_book                  invalid  Some of the inputs are invalid
     2026-11-07 23:18:25  rest  token  1            create_book                  invalid  Some of the inputs are invalid
     2026-11-07 23:18:25  rest  token  1            create_book                  ok
     2026-11-07 23:18:25  rest  token  2            create_book                  forbidden  This needs the scope books:write
     2026-11-07 23:18:25  rest  guest  -            create_book                  unauthenticated  Sign in or send a personal access token
    ```
    `audit` alone shows the latest 50 calls of every capability.
## <a name="what"></a>What is written

| A call | Written |
| --- | --- |
| succeeds, and the capability is not `readOnly` | yes, outcome `ok` |
| succeeds, and the capability is `readOnly` | no |
| is refused with a `ServiceError` | yes, outcome its code (`invalid`, `unauthenticated`, `forbidden`, `not_found`, `conflict`) and its message |
| throws any other exception | yes, outcome `error`, detail the exception's class |

The columns of `caligrafy_audit`:

| Column | Value |
| --- | --- |
| `occurred_at` | when (PHP's clock, `SERVER_TIMEZONE`) |
| `actor_type` | `user`, `token`, `key` (the legacy API key), `cli`, `guest`, or the system of a job or an event (`schedule`, `queue`, `webhook`) |
| `actor_id` | the token id or the user id, or the job's name; empty for the command line, the legacy key and guests |
| `channel` | `web`, `rest`, `mcp` or `cli` |
| `capability` | its name |
| `outcome` | `ok` or the refusal's code, or `error` |
| `detail` | a short note (the refusal's message), 500 characters at most |

A change confirmed in [Snap](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant) is also
written as `snap_confirm`, its detail what was confirmed.
## <a name="php"></a>From PHP

```php
use Caligrafy\Audit;

$rows = Audit::latest(200, 'delete_book');   // newest first, 1 to 1000 rows; the capability is optional
```

`Audit::record($context, $capability, $outcome, $detail)` writes a row yourself (it returns `false` instead of failing
when the table is missing). Show the log to administrators with a read-only capability of `level: 1` that returns
`Audit::latest()`.

Reference: [`Caligrafy\Audit`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#audit),
[`Audit::latest()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#audit-latest).
## Common mistakes

+ **Looking for the successful reads**: a read-only capability is written only when it is refused.
+ **The audit time and the `created_at` of rows differ by hours** (G65): before 2.3.0 the audit used PHP's clock and the
  `DEFAULT CURRENT_TIMESTAMP` columns MySQL's. Since 2.3.0 `Database::connect()` sets MySQL's session time zone to PHP's
  (`DB_TIMEZONE=server` keeps MySQL's); rows written before the upgrade keep their old times.
## Related pages

+ [Read-only and destructive capabilities](https://github.com/caligrafy/caligrafy-quill/wiki/Read-Only-and-Destructive-Capabilities)
+ [The context](https://github.com/caligrafy/caligrafy-quill/wiki/The-Context): the actor types
+ [Caligrafer: `audit`](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#audit)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Call-a-Capability-from-Code -->

The channels call capabilities for you: a page, a form, REST, MCP. Sometimes your own code calls one: a script, a
capability that builds on another, a controller you kept, a job, a test. This page shows each way, and what each one
checks. Since 2.1.0 (`$this->capability()` 2.21.0).
## <a name="ways"></a>The ways, side by side

| From | Call | Who it runs as | Checks, validation, audit |
| --- | --- | --- | --- |
| a terminal | `php caligrafer.php call get_book id=3` | full access (`--token`: a token, `--guest`: a visitor) | all three |
| any PHP code | `Capabilities::call('get_book', ['id' => 3], $context)` | the context you give | all three |
| a capability | `$this->capability('list_books', $input, $context)` | the same person | all three |
| a controller | `$this->call('create_book')` | the signed-in person (`Context::fromRequest($request, 'web')`) | all three |
| later, in the background | `Queue::push('send_loan_receipt', ['loan_id' => $id])` | the queue's system context | all three, when the worker runs it |
| a test | `$this->call('create_book', $input, $this->user(7))` | the user you give, or `'guest'` | all three, rolled back after the test |
| PHP, without the checks | `Container::make(GetBook::class)->run(['id' => 3])` | the command line, unless you pass a context | validation only: no access check, no audit |
## <a name="cli"></a>From the command line

```bash
php caligrafer.php call list_books
php caligrafer.php call get_book id=3
php caligrafer.php call create_book '{"title": "Dawn", "published_year": 1987, "author_id": 2}'
php caligrafer.php call create_book title=Dawn published_year=1987 author_id=2 --guest          # as a visitor who is not signed in
php caligrafer.php call create_book title=Dawn published_year=1987 author_id=2 --token cq_...   # as a token (or CALIGRAFY_TOKEN=cq_...)
```

It prints the same JSON as REST: `{"data": ...}` with exit code `0`, or `{"error": {...}}` with exit code `1`. Without
`--token` or `--guest` it has full access, like any script you run (channel `cli` in the audit log).
`php caligrafer.php capabilities` lists what there is to call.
## <a name="php"></a>From PHP: `Capabilities::call()`

```php
use Caligrafy\Capabilities;
use Caligrafy\Context;
use Caligrafy\ServiceError;

try {
    $book = Capabilities::call('get_book', ['id' => 3], Context::cli());
} catch (ServiceError $e) {
    echo json_encode($e->toArray());
}
```

`Capabilities::call($name, $input, $context, $uploads = null)` does what every channel does, in order: finds the
capability, checks the context, keeps, filters and validates the inputs, runs `handle()`, writes the audit log, and
returns plain data (models become arrays of their columns). Extra input keys are ignored. Choose the context for who
acts ([The context](https://github.com/caligrafy/caligrafy-quill/wiki/The-Context)): `Context::cli()` for full access,
`Context::system('schedule', 'nightly-report')` for work the system does on its own, `Context::forToken($row)` or
`Context::guest()` to act as a token or a visitor.
## <a name="capability"></a>From another capability: `$this->capability()`

```php
public function handle(array $input, Context $context)
{
    $books = $this->capability('list_books', array('author_id' => $input['author_id']), $context);
    // ...
}
```

It runs the other capability **as the same person**, with its checks, its validation and its audit, and throws its
`ServiceError`. This is how a [web-only capability](https://github.com/caligrafy/caligrafy-quill/wiki/Web-Only-Capabilities)
reuses the work of plain ones.
## <a name="controller"></a>From a controller you kept: `$this->call()`

```php
try { $book = $this->call('create_book'); redirect('/books/' . $book['id']); }
catch (ServiceError $e) { return view('Books/form', ['errors' => $e->fields]); }
```

Without inputs it sends the route variables and the request's parameters (the parameters win on the same name). It runs
as the signed-in person, on the `web` channel. New code does not need a controller:
[Controllers](https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers) shows how to move one to a declared route.
## <a name="run"></a>Without the checks: `Service::run()`

```php
use Caligrafy\Container;

$book = Container::make(GetBook::class)->run(['id' => 3]);
```

`run($input, $context = null)` validates the inputs and calls `handle()`, with `Context::cli()` when you give none. It
checks no access and writes no audit, and it returns what `handle()` returns (a model stays a model). `Container::make()`
builds the class with what its constructor asks for
([Dependency injection](https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection)).

Reference: [`Capabilities::call()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capabilities-call),
[`Service::run()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#service-run),
[`Controller::call()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Controller#controller-call),
[`Container::make()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#container-make).
## Common mistakes

+ **A web-only capability from code** (G143): `Capabilities::call()`, `$this->call()` and `call` answer `not_found`; only
  `Route::action` reaches it.
+ **A job capability anyone may call**: the queue runs it with full access, so it checks `$context->actorType()`
  ([Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs)).
## Related pages

+ [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App): `$this->call()`, `$this->action()`, `assertCapabilityFails()`
+ [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs) · [Scheduled jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs)
+ [Caligrafer: `call`](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#call)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs -->

A **scheduled job** runs one of your capabilities on a timer, with no page open: send a reminder every morning, clean
old rows every night, check prices every minute. You declare the jobs in one file, `application/config/schedule.php`;
Caligrafy runs them on your computer while you develop and on Caligrafy Cloud in production. Since 2.14.0.
## With Claude

```text
/caligrafy-quill:new-capability Every night at 3:00 New York time, delete the loans returned more than a year ago
```

Claude writes the capability in `application/services/`, adds the job to `application/config/schedule.php`, then runs
`php caligrafer.php schedule list` and `php caligrafer.php schedule run <job>`.

**Check**

+ The capability finds its rows itself: a job has nobody signed in, so it never reads `$context->userId()`.
+ `php caligrafer.php schedule list` shows the job with the rhythm you asked for.
+ `php caligrafer.php schedule history <job>` shows a run with `ok`.
## <a name="example"></a>By hand: clear the old loans every night

**Bookshelf** keeps every loan forever. This job deletes the loans returned more than a year ago, every night at 3:00
in New York. Start from the sign-in pages of [Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication)
(the `users` table and the Bookshelf catalog). The commands run in the Docker server of the Quickstart; without Docker,
drop `docker compose exec dev-box`.

**1. The loans table.** It is the one of the course's
[lesson 13](https://github.com/caligrafy/caligrafy-quill-course/wiki/13-Capstone-Loans). If you do not have it, write
`application/models/Loans/create_db.sql`:

```sql
CREATE TABLE IF NOT EXISTS loans (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    book_id INT UNSIGNED NOT NULL,
    borrower VARCHAR(100) NOT NULL,
    due_on DATE NOT NULL,
    returned_at DATETIME NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_loans_book_id (book_id),
    CONSTRAINT fk_loans_book_id FOREIGN KEY (book_id) REFERENCES books (id)
        ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
```

and run `docker compose exec dev-box php caligrafer.php sql application/models/Loans/create_db.sql`.

**2. The capability.** Run `docker compose exec dev-box php caligrafer.php service Loans/ClearReturnedLoans --scope loans:write`, then replace
`application/services/Loans/ClearReturnedLoans.php` with:

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;

#[Capability(
    name: 'clear_returned_loans',
    description: 'Deletes the loans returned more than a number of days ago (365 by default). Returns how many were deleted.',
    scope: 'loans:write',
    level: 1,
    destructive: true
)]
class ClearReturnedLoans extends Service
{
    public $rules = array('days' => 'integer|min_numeric,1|max_numeric,3650');
    public $descriptions = array('days' => 'Loans returned more than this many days ago are deleted (365 by default)');

    public function handle(array $input, Context $context)
    {
        $before = date('Y-m-d H:i:s', time() - (int) ($input['days'] ?? 365) * 86400);
        // delete() returns how many rows it deleted
        $deleted = Loan::whereNotNull('returned_at')->where('returned_at', '<', $before)->delete();
        return array('deleted' => $deleted);
    }
}
```

It is an ordinary capability: an administrator (`level: 1`) can also call it from a page, the REST API or an agent.

**3. The schedule.** Write `application/config/schedule.php`:

```php
<?php
return array(
    array('name' => 'clear-returned-loans', 'capability' => 'clear_returned_loans', 'input' => array('days' => 365),
        'cron' => '0 3 * * *', 'timezone' => 'America/New_York'),
);
```

**4. Check it and run it once.**

```bash
docker compose exec dev-box php caligrafer.php schedule list
```
```text
 clear-returned-loans     0 3 * * *      clear_returned_loans     America/New_York, timeout 55s
```
```bash
docker compose exec dev-box php caligrafer.php schedule run clear-returned-loans
```
```text
 clear-returned-loans: ok
```
```bash
docker compose exec dev-box php caligrafer.php schedule history
```
```text
 2026-11-07 23:19:29  clear-returned-loans     ok
```

`schedule run` prints the outcome, not the result: `docker compose exec dev-box php caligrafer.php call clear_returned_loans days=365` prints
`{"data": {"deleted": 0}}`. `docker compose exec dev-box php caligrafer.php audit` shows the run as `cli schedule clear-returned-loans
clear_returned_loans ok`.

**5. Let it run.** On your computer, the Docker server (`.bin/caligrafer server start`) has a `scheduler` container: the job runs at 3:00 every night while it is up. Without Docker, keep `php caligrafer.php schedule work` open in
a terminal. Online on Caligrafy Cloud, deploy, then check:

```bash
docker compose exec dev-box php caligrafer.php cloud deploy bookshelf
docker compose exec dev-box php caligrafer.php cloud jobs bookshelf          # clear-returned-loans, its last run and its next one
```

**Check**

+ `schedule list` prints the job (an invalid file prints every problem and exits with `2`).
+ `schedule run clear-returned-loans` prints `ok`.
+ `schedule history` has the run.

To tell people something from a job, call [`Caligrafy\Notify::user()`](https://github.com/caligrafy/caligrafy-quill/wiki/Notifications#example)
from its capability.
## <a name="declare"></a>Reference: the schedule file

`application/config/schedule.php` returns a list of jobs. No file means no jobs.

| Field | Required | Rule |
|---|---|---|
| `name` | yes | A slug (`a-z`, `0-9`, `-`), at most 40 characters, unique in the file |
| `capability` | yes | A capability of the app (`php caligrafer.php capabilities`) |
| `input` | no | Its inputs: an array that encodes to JSON, checked by the capability's rules when it runs |
| `every` | `every` or `cron` | `1m`, `5m`, `10m`, `15m`, `30m`, `1h`, `6h`, `12h` or `1d` (in UTC; `1d` is midnight UTC) |
| `cron` | `every` or `cron` | Five fields: minute, hour, day of the month, month, day of the week (`*/15 * * * *`, `0 9-17 * * mon-fri`) |
| `timezone` | no | An IANA name such as `Europe/Paris`, for `cron` only; `UTC` by default |
| `timeout` | no | Seconds, 55 by default, from 1 to 300 |
| `enabled` | no | `true` by default; `false` keeps the job declared but never run |

Any other field is an error. Background jobs ([Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs))
run through one more job of this file, on the framework's capability `queue_work`:
`array('name' => 'queue', 'capability' => 'queue_work', 'every' => '1m', 'timeout' => 55)`.

### <a name="run"></a>How a job runs

+ **With full access**, like the command line. The audit log records it with the actor type `schedule` and the job's
  name. Nobody is signed in: `$context->userId()` is `null`, so a job that works for each user finds them itself.
+ **In its own process, one run at a time.** A run that starts while the previous one is still going is skipped and
  recorded as `skipped`.
+ **Stopped at its timeout**, and recorded as `timeout`.
+ **Recorded** in `caligrafy_job_runs` (made by `php caligrafer.php platform install` and the deploy step): the job, its
  start and end, the outcome (`ok`, `error`, `timeout`, `skipped`) and a short detail. Runs older than 30 days are
  deleted.
+ **Needs the database** (`DB_ACTIVATE=true`).

### <a name="commands"></a>Commands

| Command | What it does |
|---|---|
| `php caligrafer.php schedule list` | Checks the file and lists the jobs; `--json` prints what Caligrafy Cloud reads |
| `php caligrafer.php schedule run <job>` | Runs one job now; with `--if-due`, only when it is due this minute in its timezone |
| `php caligrafer.php schedule due` | Runs every enabled job due this minute, side by side, then stops |
| `php caligrafer.php schedule work` | Runs `schedule due` at the start of every minute until you stop it |
| `php caligrafer.php schedule history [<job>] [--limit 50]` | The latest runs, newest first |

Exit codes: `0` ok, `1` the capability failed or timed out, `2` the file is invalid, `3` skipped. `php caligrafer.php
doctor` reports an invalid file too.

### <a name="develop"></a>While you develop

`.bin/caligrafer server start` starts the **scheduler** container: it runs `schedule work`, so your jobs run as they
will online. Without Docker, run `php caligrafer.php schedule work` in a terminal. Projects made before 2.14.0 get the
`scheduler` service in `docker-compose.yaml` with `php caligrafer.php update` (or `docker-compose.yaml.caligrafy-new`
when you changed the file: copy its `scheduler` service into yours).

### <a name="online"></a>Online

**Caligrafy Cloud** runs the jobs while the app is online. At each start the deploy step prints the jobs on one line of
the log (`caligrafy-schedule {...}`, the listing of `schedule list --json`), and Cloud runs each one inside the app's
container on its rhythm, with the app's code, settings and database.

| | |
|---|---|
| **See them** | `php caligrafer.php cloud jobs <app>` (each job, its last run and its next one), or **Jobs** on the app's page |
| **Run one now** | `php caligrafer.php cloud jobs <app> run <job>` (within the minute), or **Run now** |
| **Their runs** | `php caligrafer.php cloud jobs <app> history <job>` (7 days, with their output), `cloud logs <app> --jobs`. A run that has not ended shows `running`, with no duration |
| **Limits** | 20 jobs per app, once a minute at most, 300 seconds per run; included in the app's time, no extra credits |
| **Paused** | A paused app runs no jobs, and missed runs are not caught up |
| **Failing** | After 10 failed runs in a row of one job, Cloud emails you once; it never turns a job off |
| **Invalid file** | The app stays online but its jobs do not run: the app's page and an email say why. Fix the file and deploy again |

**Your own server** (Coolify, Docker): run a second container from the same image and `.env` with
`php caligrafer.php schedule work`, or `php caligrafer.php schedule due` from the system's cron every minute. One of
the two, never both.
## Common mistakes

+ **The job does nothing for "the current user".** A job has nobody signed in: find the users or rows in the capability.
+ **`'timezone' is for 'cron' only`.** `every` is always in UTC: use `cron` with a `timezone` for a time of day.
+ **A job stopped at 55 seconds.** Raise its `timeout` (300 at most), or move the work to a
  [background job](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs) (900 seconds).
+ **Jobs run twice online.** Your own server runs both `schedule work` and a cron line: keep one.
+ **Nothing runs on your computer.** The `scheduler` container is not up (`server start`), or `schedule work` is not open.
## Related pages

+ [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs)
+ [Notifications](https://github.com/caligrafy/caligrafy-quill/wiki/Notifications)
+ [Build once: services, capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP)
+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Notifications -->

**Notifications** reach your users when none of your pages are open: a book due tomorrow, a reservation ready, an
order shipped. One call, `Caligrafy\Notify::user()`, sends the message on every channel the user turned on: **web push**
(a notification on their phone or computer, browser closed) and **email** (an address they confirmed). Since 2.15.0.

**Since 2.26.0** web push needs `php caligrafer.php add push` once (web-push and an HTTP client); without it, emails still go out and push is skipped with a message in the log. `php caligrafer.php doctor` says when the VAPID keys are set but the SDK is missing.
## With Claude

```text
/caligrafy-quill:new-capability Every morning at 8, tell the administrators how many books are due today or late, and add a "Turn on alerts" button to the loans page
```

Claude writes the capability that calls `Notify::user()`, the job in `application/config/schedule.php`, the button
with `public/js/notify.js`, and adds `Route::capabilities()` and `Route::notifications()` to `web.php`. It runs
`php caligrafer.php platform install` and `php caligrafer.php notify keys --subject mailto:<you>` on your computer
(Caligrafy Cloud makes its own keys).

**Check**

+ `php caligrafer.php notify status <your user id>` shows `push` `configured: true`.
+ After *Turn on alerts* in your browser, `php caligrafer.php notify test <your user id>` answers `"push": 1` and a
  notification appears.
+ `php caligrafer.php schedule run <job>` prints `ok`.
## <a name="example"></a>By hand: tell the administrators what is late, every morning

Every morning at 8 in New York, each administrator of **Bookshelf** hears how many loans are due today or late. Start
from [Scheduled jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs#example) (the `loans` table) and
an administrator (`permissions` 1, [Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication)).
The commands run in the Docker server of the Quickstart; without Docker, drop `docker compose exec dev-box`.
The whole lesson, with a page and Caligrafy Cloud, is
[course lesson 15](https://github.com/caligrafy/caligrafy-quill-course/wiki/15-Reminders).

**1. Turn notifications on, once.**

```bash
docker compose exec dev-box php caligrafer.php platform install
docker compose exec dev-box php caligrafer.php notify keys --subject mailto:you@example.com
```

`notify keys` prints ` Web push keys written to .env (VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY, VAPID_SUBJECT=mailto:you@example.com).
Keep them: new keys cut off every subscribed browser`. Run again, it keeps them.

**2. The routes.** In `application/config/routing/web.php`, below `Route::auth(...)`:

```php
    Route::capabilities();      // what notify.js calls (/capabilities)
    Route::notifications();     // the pages the emails link to: /notify/confirm/{token}, /notify/unsubscribe
```

**3. The capability.** Write `application/services/Loans/RemindLoans.php` (the course's, lesson 15):

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Database;
use Caligrafy\Notify;
use Caligrafy\Service;

// remind_loans: tells the administrators which books are due today or late; a scheduled job runs it every morning
#[Capability(
    name: 'remind_loans',
    description: 'Notifies every administrator of the loans due today or late, by push and email. Returns how many loans are due today, how many are late, and how many administrators got the message.',
    scope: 'loans:write',
    level: 1
)]
class RemindLoans extends Service
{
    public function handle(array $input, Context $context)
    {
        $today = date('Y-m-d');
        $due = Loan::whereNull('returned_at')->where('due_on', $today)->count();         // SELECT COUNT(*)
        $late = Loan::whereNull('returned_at')->where('due_on', '<', $today)->count();
        if ($due + $late === 0) {
            return array('due' => 0, 'late' => 0, 'notified' => 0);
        }
        $books = $due + $late;
        $message = array(
            'title' => $books === 1 ? '1 book to bring back' : "$books books to bring back",
            'body' => "$due due today, $late late. Open the loans to see who has them.",
            'url' => '/loans',
            'tag' => 'loans-due'
        );
        $notified = 0;
        foreach (Database::table('users')->where('permissions', '>=', 1)->pluck('id') as $admin) {
            $sent = Notify::user($admin, $message);
            if ($sent['push'] > 0 || $sent['email']) {
                $notified++;
            }
        }
        return array('due' => $due, 'late' => $late, 'notified' => $notified);
    }
}
```

A job has nobody signed in, so the capability finds the people it notifies itself.

**4. The schedule.** Add the job to `application/config/schedule.php`:

```php
<?php
return array(
    array('name' => 'clear-returned-loans', 'capability' => 'clear_returned_loans', 'input' => array('days' => 365),
        'cron' => '0 3 * * *', 'timezone' => 'America/New_York'),
    array('name' => 'remind-loans', 'capability' => 'remind_loans', 'cron' => '0 8 * * *', 'timezone' => 'America/New_York'),
);
```

**5. <a name="page"></a>The button.** Push needs the user's permission, asked from a click. Add to the loans page of
the course, `application/views/Loans/index.pug`, at the end of `block content`:

```pug
    button.btn.btn-primary#alerts(type='button') Turn on alerts
    script(src=$home . 'public/js/notify.js')
    script.
      document.getElementById('alerts').addEventListener('click', async () => {
        const status = await Notify.enable()
        if (status === 'install-needed') alert('On iPhone and iPad, add the app to your Home Screen first')
      })
```

**6. Try it.** Sign in as the administrator, open `http://localhost:8080/loans`, press *Turn on alerts* and allow notifications. Then:

```bash
docker compose exec dev-box php caligrafer.php notify test 1          # 1: the administrator's user id
```
```json
{
    "push": 1,
    "email": false,
    "skipped": null
}
```

A *Notifications work* message appears. With a loan due today or late:

```bash
docker compose exec dev-box php caligrafer.php schedule run remind-loans     # remind-loans: ok
docker compose exec dev-box php caligrafer.php call remind_loans             # {"data": {"due": 0, "late": 1, "notified": 1}}
```

Before any browser turned push on, the same calls answer `"push": 0` and `"notified": 0`: nothing is sent, nothing
fails.

**Check**

+ `docker compose exec dev-box php caligrafer.php notify status 1` lists `"browsers": 1` under `push`.
+ The *1 book to bring back* notification opens `/loans` on a tap.
+ The table `caligrafy_notifications` has one line per message (never its body).
## <a name="send"></a>Reference: `Notify::user`

```php
$result = Caligrafy\Notify::user($userId, array(
    'title'   => 'Kindred is due tomorrow', // required, at most 80 characters
    'body'    => 'Bring it back by Friday.', // required, at most 300 characters
    'url'     => '/books/3',               // opened on a tap: a path of the app, or an https:// address
    'tag'     => 'loan-17',                // optional: a new message with the same tag replaces the old one
    'urgency' => 'high',                   // optional: low, normal (default) or high
));
// array('push' => 1, 'email' => true, 'skipped' => null)
```

+ `$userId` is the id `$context->userId()` gives (in a job, the id of each user it works for).
+ `push` is how many browsers got it; `email` whether an email was sent.
+ A delivery failure never throws. A bad message throws `ServiceError::invalid` with the fields.
+ At most `NOTIFY_RATE_PER_HOUR` messages per user and hour (30): above it nothing is sent (`'skipped' => 'rate'`).
+ Every call is logged in `caligrafy_notifications` (who, the title, the tag, what each channel did; never the body),
  kept 30 days.
+ Without the tables (`platform install`) nothing is sent and nothing fails.
+ When you delete a user, call `Caligrafy\Notify::forget($userId)`: their browsers, address, choices and log go.

### <a name="setup"></a>Settings

| `.env` | Default | |
|---|---|---|
| `NOTIFY_CHANNELS` | `push,email` | The channels the app offers |
| `NOTIFY_RATE_PER_HOUR` | `30` | Messages per user and hour |
| `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY`, `VAPID_SUBJECT` | empty | Written by `notify keys`; never replaced (new keys cut off every subscribed browser) |
| `APP_URL` | empty | The app's address, for the links of emails sent by jobs and the command line (Caligrafy Cloud sets it) |
| `MAIL_HOST`, `MAIL_PORT`, `MAIL_USERNAME`, `MAIL_PASSWORD`, `MAIL_FROM` | | The emails' server and sender; without them email reports `not-configured` and push still works |

On **Caligrafy Cloud** each app gets its web push keys at its first deploy, kept across deploys.

| Command | |
|---|---|
| `php caligrafer.php notify keys [--subject mailto:you@example.com]` | writes the web push keys to `.env`, once |
| `php caligrafer.php notify test <user id>` | sends that user a test message on every channel they turned on |
| `php caligrafer.php notify status <user id>` | the channels, the browsers, the email address and whether it is confirmed |

### `notify.js`

| | |
|---|---|
| `Notify.status()` | `unsupported`, `install-needed` (iPhone and iPad outside the Home Screen app), `denied`, `off` or `on` |
| `Notify.enable()` | asks permission, subscribes this browser, saves it; returns the new status. Call it from a click |
| `Notify.disable()` | unsubscribes this browser |
| `Notify.test()` | sends a test message to the signed-in user |
| `Notify.email(address)` | sets the address and emails a link to confirm it (24 hours) |
| `Notify.channel('email', false)` | turns a channel off (or on) |
| `Notify.info()` | what `notify_status` answers |

It registers `public/sw.js`, which shows the message with the browser closed and, on a tap, focuses a tab of its
address or opens one. Keep an in-page banner for when a page is open: notifications are for when it is not.

### <a name="email"></a>Email

+ **Only to a confirmed address.** `Notify.email()` (the `notify_email_set` capability) sends a link valid 24 hours,
  used once. Nothing else is sent there before.
+ **Unsubscribe in one click:** every email has a signed link and the `List-Unsubscribe` and `List-Unsubscribe-Post`
  headers that mail apps show as a button (`Route::notifications()` answers them).
+ **In your app's look:** the emails take the colors, font and corners of your
  [design style](https://github.com/caligrafy/caligrafy-quill/wiki/Design-Styles) (`DESIGN_STYLE`), else Caligrafy's.

### <a name="capabilities"></a>Built-in capabilities

They ship with the framework, so pages, REST and the JS client use them with no code of yours. Each acts only on the
signed-in user's own data; none is an MCP tool (only a browser can subscribe or open a link).

| Capability | Input |
|---|---|
| `notify_status` | none: the channels and their state |
| `notify_subscribe` | the browser's `PushSubscription` JSON |
| `notify_unsubscribe` | `endpoint` |
| `notify_email_set` | `email` (sends the confirmation) |
| `notify_email_confirm` | `token` (public: the email's link) |
| `notify_preferences` | `channel`, `enabled` |
| `notify_test` | none |

### <a name="devices"></a>Where push works

Chrome, Edge and Firefox on computers and Android; Safari on Mac; Safari on iPhone and iPad once the app is added to
the Home Screen ([install to home screen](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#install)). A
device that is off gets the message when it comes back, within 24 hours. Push needs HTTPS (or `localhost`).
## Common mistakes

+ **`Notify.enable()` does nothing.** It was called on page load: browsers ask permission only from a click.
+ **`"push": 0` for everyone.** No browser turned push on yet, or the VAPID keys changed (`notify keys` was run on a new
  `.env`): every browser must turn it on again.
+ **Emails from a job have no links.** `APP_URL` is empty: set it to the app's address.
+ **`"email": false`.** The user has no confirmed address, or `MAIL_*` is not set.
+ **Nothing on iPhone.** The app must be added to the Home Screen, and served over HTTPS.
## Related pages

+ [Scheduled jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs)
+ [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs)
+ [Views: install to home screen](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#install)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs -->

A **background job** runs one of your capabilities later, outside the request: the page answers at once, and the slow
part (an email, an AI call, a report, resizing images) happens a moment after, with retries when it fails. A job is a
capability's name and its input, pushed with `Caligrafy\Queue::push()` and run by a worker. Since 2.18.0.
## With Claude

```text
/caligrafy-quill:new-capability When a book is lent, notify the person who lent it of its due date, in the background
```

Claude writes two capabilities, the one the page calls (it checks who asks, saves, then pushes the job) and the one that
does the work, and adds the worker job on `queue_work` to `application/config/schedule.php`.

**Check**

+ The capability that pushes checks who may ask, and pushes ids, not data to trust later.
+ The work capability refuses callers other than the queue (it runs with full access).
+ `php caligrafer.php queue work --once` prints `done` for the job.
## By hand: a receipt for each loan

When the front desk of **Bookshelf** lends a book, the call answers at once, and a job tells the person who lent it who
has the book and until when. Start from the loans of the course
([lesson 13](https://github.com/caligrafy/caligrafy-quill-course/wiki/13-Capstone-Loans): the `loans` table, the `Loan`
model, `lend_book`) and from [Notifications](https://github.com/caligrafy/caligrafy-quill/wiki/Notifications#example)
(`platform install`, `notify keys`). The commands run in the Docker server of the Quickstart; without Docker, drop
`docker compose exec dev-box`.

**1. <a name="push"></a>Push the job from the capability that takes the request.** Replace
`application/services/Loans/LendBook.php` with (the course's, plus `use Caligrafy\Queue;` and the `Queue::push` line):

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Queue;
use Caligrafy\Service;
use Caligrafy\ServiceError;

// lend_book: records that someone borrowed a book, for a number of days
#[Capability(
    name: 'lend_book',
    description: 'Lends a book of the catalog to someone for a number of days (14 by default) and returns the loan. Refused when the book is already lent.',
    scope: 'loans:write'
)]
class LendBook extends Service
{
    public $rules = array('book_id' => 'required|integer', 'borrower' => 'required|max_len,100', 'days' => 'integer|min_numeric,1|max_numeric,60');
    public $filters = array('borrower' => 'trim');
    public $descriptions = array(
        'book_id' => 'The id of the book (list_books, search_books)',
        'borrower' => 'The name of the person who borrows it',
        'days' => 'For how many days: 1 to 60, 14 by default'
    );

    public function handle(array $input, Context $context)
    {
        if (!Book::find($input['book_id'])) {
            throw ServiceError::notFound("There is no book #{$input['book_id']}");
        }
        $open = Loan::where('book_id', $input['book_id'])->whereNull('returned_at')->first();
        if ($open) {
            throw ServiceError::conflict("This book is already lent to {$open->borrower}");
        }
        $days = (int) ($input['days'] ?? 14);
        $id = Loan::insert(array(
            'book_id' => $input['book_id'],
            'borrower' => $input['borrower'],
            'due_on' => date('Y-m-d', strtotime("+$days days"))
        ));
        if ($context->userId() !== null) {
            // later, outside the request: tell the person who lent it
            Queue::push('send_loan_receipt', array('loan_id' => (int) $id, 'user_id' => (int) $context->userId()));
        }
        return Loan::find($id);
    }
}
```

The job gets ids, not names or dates to trust later, and only when someone is behind the call.

**2. The capability that does the work.** Write `application/services/Loans/SendLoanReceipt.php`:

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Notify;
use Caligrafy\Service;
use Caligrafy\ServiceError;

// send_loan_receipt: run by the queue after lend_book, tells the person who lent the book when it comes back
#[Capability(
    name: 'send_loan_receipt',
    description: 'Tells the person who lent a book who has it and when it is due. Run by the queue after lend_book.',
    mcp: false
)]
class SendLoanReceipt extends Service
{
    public $rules = array('loan_id' => 'required|integer', 'user_id' => 'required|integer');

    public function handle(array $input, Context $context)
    {
        if (!in_array($context->actorType(), array('queue', 'cli'), true)) {
            throw ServiceError::forbidden('The queue sends the loan receipts');
        }
        $loan = Loan::find($input['loan_id']);
        if (!$loan) {
            throw ServiceError::notFound("There is no loan #{$input['loan_id']}");
        }
        $book = Book::find($loan->book_id);
        $sent = Notify::user($input['user_id'], array(
            'title' => $book->title . ' is lent',
            'body' => $loan->borrower . ' has it until ' . $loan->due_on . '.',
            'url' => '/loans',
            'tag' => 'loan-' . $loan->id,
        ));
        return array('loan_id' => (int) $loan->id, 'push' => $sent['push'], 'email' => $sent['email']);
    }
}
```

The job runs with full access: the `actorType()` check keeps people from calling it through the REST API.

**3. The worker.** Add the queue to `application/config/schedule.php`:

```php
<?php
return array(
    array('name' => 'clear-returned-loans', 'capability' => 'clear_returned_loans', 'input' => array('days' => 365),
        'cron' => '0 3 * * *', 'timezone' => 'America/New_York'),
    array('name' => 'remind-loans', 'capability' => 'remind_loans', 'cron' => '0 8 * * *', 'timezone' => 'America/New_York'),
    array('name' => 'queue', 'capability' => 'queue_work', 'every' => '1m', 'timeout' => 55),
);
```

Every minute it runs the jobs that are due for up to 50 seconds: the `scheduler` container of the Docker server and
Caligrafy Cloud run it.

**4. Try it.** Lend a book as the front desk, with a token that acts for the administrator (user 1), through the REST
API (`Route::capabilities()` in `web.php`):

```bash
docker compose exec dev-box php caligrafer.php token create "Front desk" --scopes loans:write --user 1
curl -X POST -H "Authorization: Bearer cq_<id>_<secret>" -H "Content-Type: application/json" \
  -d '{"book_id": 1, "borrower": "Sam"}' http://localhost:8080/capabilities/lend_book
```

It answers at once: `201 {"data":{"id":1,"book_id":1,"borrower":"Sam","due_on":"<in 14 days>",...}}`. The same call again
answers `409 {"error":{"code":"conflict","message":"This book is already lent to Sam"}}`. The job waits:

```bash
docker compose exec dev-box php caligrafer.php queue list
```
```text
 #1      default  send_loan_receipt        pending  0/3  from 2026-11-07 23:40:15
```

Run it now (the scheduler's `queue` job does the same within a minute):

```bash
docker compose exec dev-box php caligrafer.php queue work --once
```
```text
 Working the queue default until it is empty
 #1 send_loan_receipt: done
 1 done, 0 to try again, 0 failed
```

The notification *A Wizard of Earthsea is lent* reaches the administrator's browsers if they turned alerts on.

**Check**

+ `queue status` reads `0 pending, 0 running, 1 done, 0 failed`.
+ `audit` has `queue send_loan_receipt #1 send_loan_receipt ok`.
+ The `lend_book` call answered before the job ran.
## Reference: `Queue::push`

```php
use Caligrafy\Queue;

Queue::push('send_loan_receipt', ['loan_id' => $id, 'user_id' => $userId]);
Queue::push('build_report', ['month' => '2026-11'], ['delay' => 600, 'attempts' => 5, 'timeout' => 120]);
```

| Option | Default | What it does |
|---|---|---|
| `delay` | `0` | seconds before the job may start |
| `attempts` | `3` | how many times it is tried (1 to 20) |
| `timeout` | `60` | seconds a run may take before it is stopped (900 at most) |
| `queue` | `default` | the queue's name (lowercase letters, digits, `-`, `_`), for a worker of its own |

+ It returns the job's id. The capability must exist when you push (`InvalidArgumentException` otherwise), and the
  input must encode to JSON.
+ Jobs are kept in `caligrafy_jobs` (made by `php caligrafer.php platform install` and the deploy step).
+ **Who it runs as.** A job runs with full access, like a scheduled job (`Context::system`: the audit log records
  `queue` and `<capability> #<id>`). Check who may ask for the work before you push it, and pass ids rather than data
  to trust later.

### Workers

| Way | When |
|---|---|
| a job on `queue_work` in `schedule.php` (`'every' => '1m', 'timeout' => 55`) | Caligrafy Cloud, and `server start` on your computer; a job starts within a minute and has what is left of it |
| `php caligrafer.php queue work` | your own server, longer jobs: a loop that runs jobs as they come (Ctrl+C stops it) |

```bash
php caligrafer.php queue work                 # runs jobs as they come
php caligrafer.php queue work --once          # runs what is due, then stops
php caligrafer.php queue work --for 300       # for 5 minutes
php caligrafer.php queue work --queue reports --sleep 3   # another queue; seconds between looks when empty
```

Each job runs in its own process, stopped at its timeout. Run one way or the other, not both. `queue_work` takes
`queue` and `seconds` (1 to 290, default 50) inputs, and refuses every caller but the scheduler and the command line.

### <a name="failures"></a>Failures and retries

+ A run that throws or times out is tried again after 30 seconds, then 1 minute, 2 minutes... until its attempts are
  used; then the job is `failed`.
+ A refusal of the capability (`invalid`, `not_found`, `forbidden`, `unauthenticated`) fails at once: it would fail
  again. `queue work` prints `#2 send_loan_receipt: failed (There is no loan #999)`.
+ A worker that stopped in the middle of a job (a restart) leaves it `running`; the next worker puts it back once its
  timeout and one more minute have passed.
+ Finished jobs are kept 7 days.

```bash
php caligrafer.php queue status              # pending, running, done, failed
php caligrafer.php queue list                # the latest jobs, with their last error (--status failed, --limit 50)
php caligrafer.php queue failed              # only the failed ones
php caligrafer.php queue retry 42            # or: queue retry all
```

### <a name="test"></a>Testing

In a test, `$this->assertQueued('send_loan_receipt')` checks that a job was pushed and returns its input
([Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App)). Run the job itself with
`$this->call('send_loan_receipt', $input)`.
## Common mistakes

+ **Jobs stay `pending`.** No worker: add the `queue` job to `schedule.php`, or run `queue work`.
+ **Two workers for one queue.** A `queue_work` job and a `queue work` container side by side: keep one.
+ **A job reads the signed-in user.** Nobody is signed in when it runs: pass the ids it needs in its input.
+ **Anyone can trigger the work.** The work capability is also a REST capability: refuse callers whose
  `$context->actorType()` is not `queue` (or `cli`).
+ **A long job is stopped at 50 seconds** with the scheduler's worker: give it a worker of its own (`queue work`,
  timeouts up to 900 seconds).
## Related pages

+ [Scheduled jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs)
+ [Notifications](https://github.com/caligrafy/caligrafy-quill/wiki/Notifications)
+ [Snap Cards: a capability declared `async: true` runs in the queue as a Track card: Task](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant#tasks)
+ [Authentication: tokens](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#agents)
+ [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Migrations -->

A **migration** is one change to a table that already holds data, written as a numbered SQL file that runs once. Every
computer and every server runs the same files in the same order, so they all end up with the same tables. Since 2.18.0.

**Which file to write:**

| You want to... | Write | Run it with |
|---|---|---|
| create a new table (its first version) | `CREATE TABLE IF NOT EXISTS` in `application/models/<Folder>/create_db.sql` ([Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models)) | `php caligrafer.php sql application/models/<Folder>/create_db.sql` |
| change a table that holds data: add a column or an index, rename, fix rows | a migration in `application/migrations/` (this page) | `php caligrafer.php migrate` |

A `create_db.sql` that already ran is never edited: once a table has rows, every change to it goes in a new migration.
## With Claude

Ask for the change with the `db` skill of the Claude Code plugin:

```text
/caligrafy-quill:db add an isbn column (20 characters, optional, unique) to the books table
```

Claude writes `application/migrations/<number>_<name>.sql` with `php caligrafer.php migrate make <name>`, puts the SQL
in it, runs `php caligrafer.php migrate` (in the Docker container when the project uses the Docker server) and checks
`php caligrafer.php migrate status`. It never edits a migration that already ran.

**Check** before you say OK:
+ the new file is in `application/migrations/` and holds one change;
+ `php caligrafer.php migrate status` shows every file as `ran`;
+ the model of the table has a property for each new column (`public $isbn;`).
## <a name="write"></a>By hand

The Bookshelf `books` table exists and holds rows ([Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models)).
Add an `isbn` column to it. With the Docker server of the
[Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart), run every command in the container:
`docker compose exec dev-box php caligrafer.php ...` (without Docker, drop `docker compose exec dev-box`).

1. **Create the file.** Run:
    ```bash
    docker compose exec dev-box php caligrafer.php migrate make add_books_isbn
    ```
    It prints the file it wrote (the number is the date and time):
    ```text
     application/migrations/20261107120200_add_books_isbn.sql written: add its SQL, then php caligrafer.php migrate
    ```
2. **Write the change.** Open that file and make it read:
    ```sql
    -- add_books_isbn
    -- Runs once (php caligrafer.php migrate, and at every deploy). Never edit it after it ran: write a new one.
    -- One statement: the column and its unique index are added together, or not at all.

    ALTER TABLE books
        ADD COLUMN isbn VARCHAR(20) NULL AFTER summary,
        ADD UNIQUE KEY uq_books_isbn (isbn);
    ```
    Two books never share an ISBN, and a book without one has `NULL`, which the unique index allows on many rows.
3. **See what will run.** Run:
    ```bash
    docker compose exec dev-box php caligrafer.php migrate status
    ```
    ```text
     pending  20261107120200_add_books_isbn.sql
    ```
4. **Run it.** Run:
    ```bash
    docker compose exec dev-box php caligrafer.php migrate
    ```
    ```text
     OK   20261107120200_add_books_isbn.sql

     1 migration(s) run on caligrafy
    ```
    Run it again and it says ` Nothing to migrate: caligrafy is up to date`.
5. **Give the model the new column.** In `application/models/Bookshelf/Book.php`, add `public $isbn;` after
   `public $summary;` (the whole model is on the [Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models) page).
6. **Commit the file.** It runs online on its own: the deploy step (`php caligrafer.php deploy`, which the production
   image runs at every start, and so Caligrafy Cloud) runs the pending migrations after the `create_db.sql` scripts.

**Check:**
+ `docker compose exec dev-box php caligrafer.php migrate status` shows ` ran      20261107120200_add_books_isbn.sql  (<date and time>)`;
+ `docker compose exec dev-box php caligrafer.php doctor --only database` shows `OK    Migrations: 1 ran, none pending`;
+ the column is there: `docker compose exec mysql mysql -uroot -proot caligrafy -e "DESCRIBE books"` lists
  `isbn  varchar(20)  YES  UNI  NULL`.
## <a name="run"></a>Reference

**Commands**

| Command | What it does |
|---|---|
| `php caligrafer.php migrate make <name>` | writes `application/migrations/<YYYYMMDDHHMMSS>_<name>.sql` with a comment header (the name becomes lower case, letters, digits and `_`). Needs no database |
| `php caligrafer.php migrate` | runs, in number order, every file that never ran on this database, and records each one |
| `php caligrafer.php migrate status` | each file with its state: `pending`, `ran` (with when) or `changed` |
| `php caligrafer.php migrate --env .env.testing` | the same on the database of another `.env` file, here the test database; `--env` goes with `migrate` and `migrate status` (2.19.1; before, write `migrate "" --env .env.testing`) |
| `php caligrafer.php doctor` | `WARN Migrations: 1 pending: ...` or `... changed after it ran: it will not run again`; `OK Migrations: N ran, none pending` |
| `php caligrafer.php deploy` | (production start) runs the `create_db.sql` scripts, then the pending migrations: `OK Migrations: 1 run: <name>` or `up to date`. A failing migration stops it with exit 1 |

**Files**

+ Named `<number>_<name>.sql`: the number is 1 to 14 digits, the name letters, digits and `_`. Another `.sql` name in
  the folder stops every command: `notes.sql: a migration is named <number>_<name>.sql, e.g. 20261107120000_add_books_isbn.sql`.
+ Two files with the same number (as a number: `5_a.sql` and `005_b.sql`) are refused.
+ The statements are split on `;` outside quotes (`'...'`, `"..."`, `` `...` ``) and comments (`-- `, `#`, `/* */`),
  so text such as `'a;b'` is safe. `DELIMITER` is not supported: write triggers and procedures in a script you run
  with `php caligrafer.php sql <file>`.
+ An empty file runs and is recorded: write its SQL before you run `migrate`.

**The table `caligrafy_migrations`** (made by `php caligrafer.php platform install`, or by the first `migrate`): `name`
(the file name), `sha256` (of its content when it ran) and `ran_at`. A file whose content no longer matches its
`sha256` is `changed`: it is never run again.
## <a name="rules"></a>Three rules

1. **Never edit a migration that ran.** It will not run again: `status` shows `changed`, and `migrate` prints
   ` WARN <name>: changed after it ran, not run again (write a new migration for the change)`. Put the file back as it
   was and write a new one.
2. **Forward only.** There is no "down": to undo a change, write a migration that undoes it.
3. **One change per file, or files that can run twice.** MySQL saves a `CREATE` or an `ALTER` at once. When the second
   statement of a file fails, the first one stays applied and the file is not recorded:
   ```text
    migrate: 20261107120300_add_more.sql, statement 2: SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'isbn'
   ```
   Keep one change per file, or write it so that it can run again (`CREATE TABLE IF NOT EXISTS`).
## <a name="createdb"></a>Migrations and create_db.sql

`create_db.sql` gives a new database its tables: `php caligrafer.php sql <file>` runs it by hand, and the deploy step
runs it when it is new or changed (a changed script that drops or deletes data is not run again: it says so in a `WARN`
line). A migration runs exactly once on each database, in order, after the scripts. So:

+ a new table: `create_db.sql` (its first version, `CREATE TABLE IF NOT EXISTS`);
+ any change to a table that holds data: a migration;
+ sample rows for your computer: a `seed.sql` you run with `php caligrafer.php sql` (the deploy step never runs it).
## Common mistakes

+ **Editing the file after it ran** (G120): nothing happens on any database. Restore it and write a new migration.
+ **Changing `create_db.sql` instead of writing a migration**: a database that already has the table keeps the old
  one (`CREATE TABLE IF NOT EXISTS` skips it).
+ **A table change inside a transaction or a test**: MySQL ends the transaction at the first `CREATE` or `ALTER`.
  Keep table changes in migrations.
+ **Forgetting the model**: the new column is still read and written (the rows carry it), but the model no longer
  says what the table holds. Add its property in the same change.
## Related pages

+ [Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models): the first version of a table, and its model
+ [Caligrafer: migrate](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#migrate)
+ [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App): migrations on a test database
+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online): the deploy step


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Caching -->

The **cache** keeps a value for a while, so that slow work (a call to another service, a heavy count, a report) is done
once and read many times. A capability reads through the cache, and the capabilities that change the data forget the
value, so nobody reads an old copy for long. Since 2.18.0.

**Since 2.26.0** whole answers can be cached too: a public read-only capability with `cache: <seconds>`, or a page with `Route::page(..., ['cache' => <seconds>])`, is kept in the production image's memory and answered without PHP: see [performance and deployment](https://github.com/caligrafy/caligrafy-quill/wiki/Performance-and-Deployment).
## With Claude

Say what is slow, how old the answer may be, and what changes it:

```text
/caligrafy-quill:new-capability shelf_stats books:read read-only public: the numbers of books, authors and open loans, at most 10 minutes old; forget them when a book is added
```

Claude reads the value with `Caligrafy\Cache::remember('<key>', <seconds>, fn () => ...)` in the capability, and calls
`Cache::forget('<key>')` in the capabilities that change the data.

**Check** before you say OK:
+ the key says what the value is (`bookshelf:stats`), and holds the user's id when the value is someone's;
+ every capability that changes the data forgets the key;
+ the value is plain data (numbers, strings, arrays), not a model object.
## <a name="use"></a>By hand

Run the commands in the Docker container (`docker compose exec dev-box php caligrafer.php ...`; without Docker, drop
`docker compose exec dev-box`).

1. **The framework tables.** The cache is kept in the `caligrafy_cache` table by default.
   `docker compose exec dev-box php caligrafer.php platform install` creates it (the deploy step does too).
2. **Read through the cache.** Run
   `docker compose exec dev-box php caligrafer.php service Bookshelf/ShelfStats --scope books:read --read-only`, then
   make `application/services/Bookshelf/ShelfStats.php` read:
    ```php
    <?php

    use Caligrafy\Cache;
    use Caligrafy\Capability;
    use Caligrafy\Context;
    use Caligrafy\Database;
    use Caligrafy\Service;

    #[Capability(
        name: 'shelf_stats',
        description: 'Returns the numbers of the Bookshelf: books, authors, and books out on loan now. Up to 10 minutes old.',
        scope: 'books:read',
        readOnly: true,
        public: true
    )]
    class ShelfStats extends Service
    {
        public function handle(array $input, Context $context)
        {
            return Cache::remember('bookshelf:stats', 600, function () {
                return array(
                    'books' => Database::table('books')->count(),
                    'authors' => Database::table('authors')->count(),
                    'out' => Database::table('loans')->whereNull('returned_at')->count()
                );
            });
        }
    }
    ```
    `remember()` returns the kept value when there is one, otherwise runs the function, keeps its result for 600
    seconds and returns it.
3. **Forget it where the data changes.** In `application/services/Bookshelf/CreateBook.php` (from
   [Build once](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#service)),
   add `use Caligrafy\Cache;` under `<?php` and make `handle()` read:
    ```php
        public function handle(array $input, Context $context)
        {
            $id = Book::insert($input);
            Cache::forget('bookshelf:stats');   // the number of books changed
            return Book::with('author')->find($id);
        }
    ```
    Do the same in `delete_book` and `lend_book`.
4. **Run it.** With the sample rows of [Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models):
    ```bash
    docker compose exec dev-box php caligrafer.php call shelf_stats
    ```
    ```json
    {
        "data": {
            "books": 5,
            "authors": 3,
            "out": 2
        }
    }
    ```
    The value is now in the table: `docker compose exec mysql mysql -uroot -proot caligrafy -e "SELECT cache_key, value FROM caligrafy_cache"`
    shows `bookshelf:stats  {"books":5,"authors":3,"out":2}`. Add a book with `call create_book`: the row is gone,
    and the next `call shelf_stats` says `"books": 6`.

**Check:**
+ two `call shelf_stats` in a row give the same answer, and the second one runs no count;
+ after `create_book`, `shelf_stats` has the new number;
+ `docker compose exec dev-box php caligrafer.php cache clear` prints
  ` Cache (database) emptied; <n> compiled view and class map file(s) removed`.
## Reference

```php
use Caligrafy\Cache;

Cache::remember('bookshelf:stats', 600, fn () => $this->count());   // the kept value, or the function's, kept 600 s
Cache::put('report:2026-11', $rows, 3600);    // for an hour (null: until forgotten; 0 or less: forgets it)
Cache::get('report:2026-11', []);             // the value, or [] when it is not there or too old
Cache::has('report:2026-11');                 // true or false
Cache::forever('settings', $settings);        // until it is forgotten
Cache::forget('report:2026-11');              // gone
Cache::flush();                               // the whole store
```

+ Values are stored as JSON: strings, numbers, booleans, `null` and arrays. An object (a model) comes back as an array,
  and `remember()` returns what a later read returns. A value that cannot be encoded is refused.
+ A key is any text but empty. Put whose it is in the key when it is someone's: `"loans:user:$id"`.
+ In one request, a value read once is read from memory after that.

### <a name="stores"></a>Where values are kept: `CACHE_STORE`

| `CACHE_STORE` in `.env` | Used when empty | Where |
|---|---|---|
| `database` | with `DB_ACTIVATE=true` | the `caligrafy_cache` table: one store for the web server, the queue, the scheduled jobs and every server of the app |
| `file` | without a database | a private folder of the temporary directory: one server, one system user |
| `off` | | nothing is kept; `remember()` always runs its function |

Another value stops with `CACHE_STORE=<value>: use file, database or off`. Until the `caligrafy_cache` table exists,
the database store uses the file store and writes `Caligrafy cache: the caligrafy_cache table is missing (php
caligrafer.php platform install): using the file store` in the PHP error log. One write in a hundred removes the
expired rows.

**Why the database by default:** the web server and the command line (the queue, scheduled jobs) run as different
system users, and each one has its own file store. A job that forgets a value in the file store would leave the web
server's copy in place. The database is one store for all of them.

`php caligrafer.php cache clear` empties the store, and the compiled views and the class map of the system user that
runs it. The web server keeps its own: run it as that user, or restart the container.
## Common mistakes

+ **Not forgetting** a value where the data changes: people read the old copy until it expires.
+ **`CACHE_STORE=file` with a queue or scheduled jobs** (G119): the job's `forget()` does not reach the page's copy.
  Keep the database store.
+ **Caching someone's data under a shared key**: one person sees another's. Put the user's id in the key.
+ **Expecting a model back**: it comes back as an array (`$stats['books']`).
## Related pages

+ [Build once](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP): capabilities
+ [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs): slow work done later
+ [Caligrafer: cache](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#cache)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App -->

Your app's **tests** check what it does through its capabilities, the way its pages, REST API, Vue apps and AI agents
reach them: with the permission checks, the validation and the audit. Each test runs in a database transaction that
is rolled back at its end, so tests leave the database as they found it. Since 2.18.0.
## With Claude

The `new-capability` skill writes a test with each capability. To test what exists, ask:

```text
/caligrafy-quill:new-capability write the tests of create_book, get_book and lend_book: the rule cases as a user, the refusals as a guest
```

Claude runs `php caligrafer.php test make <Name>`, fills `tests/<Name>Test.php` (extends `Caligrafy\Testing\TestCase`)
with `$this->call(...)` and `$this->assertCapabilityFails(...)`, and runs `php caligrafer.php test <Name>`.

**Check** before you say OK:
+ every refusal kind the capability can give has its assertion (`invalid`, `unauthenticated`, `forbidden`, `not_found`, `conflict`);
+ the tests create their own rows: they do not count on the rows of your development database;
+ `php caligrafer.php test` ends with `OK (...)`.
## <a name="first"></a>By hand

The tests of the Bookshelf capabilities (`create_book`, `list_books`, `get_book`, `delete_book` of
[Build once](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#service)
and `lend_book` of [Dependency injection](https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection), on
the `loans` table of [Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models)). `create_book` is closed
there (signed in or a token) and `delete_book` has `level: 1`.
PHPUnit comes with the development packages of every project (`composer install`). Run the commands in the Docker
container (`docker compose exec dev-box php caligrafer.php ...`; without Docker, drop `docker compose exec dev-box`).

1. **A database for the tests.** Copy the settings: `cp .env .env.testing`. In `.env.testing`, change one line:
    ```text
    DB_DATABASE=caligrafy_test
    ```
    `.env.testing` holds the same secrets as `.env`: the project's `.gitignore` already leaves it out of git (every
    `.env.*` file but `.env.example`, 2.19.1). Then create the database and its tables:
    ```bash
    docker compose exec mysql mysql -uroot -proot -e "CREATE DATABASE IF NOT EXISTS caligrafy_test"
    docker compose exec dev-box php caligrafer.php platform install --env .env.testing
    docker compose exec dev-box php caligrafer.php sql application/models/Bookshelf/create_db.sql --env .env.testing
    docker compose exec dev-box php caligrafer.php migrate --env .env.testing
    ```
    `--env .env.testing` runs the command on the test database (` application/models/Bookshelf/create_db.sql run on
    caligrafy_test`, ` 1 migration(s) run on caligrafy_test`). The tests
    read `.env`, then `.env.testing`, whose settings win.
2. **Create the test file.** Run:
    ```bash
    docker compose exec dev-box php caligrafer.php test make Bookshelf
    ```
    ```text
     tests/BookshelfTest.php written: php caligrafer.php test Bookshelf
    ```
3. **Write the tests.** Make `tests/BookshelfTest.php` read:
    ```php
    <?php

    use Caligrafy\Database;
    use Caligrafy\Testing\TestCase;

    /**
     * php caligrafer.php test Bookshelf
     */
    final class BookshelfTest extends TestCase
    {
        private function author(): int
        {
            // a row for this test only: the transaction of the test is rolled back at its end
            return (int) Database::table('authors')->insert(array('name' => 'Ursula K. Le Guin'));
        }

        public function testAReaderAddsABookAndEveryoneSeesIt(): void
        {
            $authorId = $this->author();
            $book = $this->call('create_book', array('title' => 'Tehanu', 'published_year' => 1990, 'author_id' => $authorId), $this->user(7));

            $this->assertSame('Tehanu', $book['title']);
            $this->assertSame('Ursula K. Le Guin', $book['author']['name']);
            $page = $this->call('list_books', array('author_id' => $authorId), 'guest');
            $this->assertSame(1, $page['total']);
            $this->assertSame('Tehanu', $page['data'][0]['title']);
        }

        public function testRefusals(): void
        {
            $error = $this->assertCapabilityFails('invalid', 'create_book', array('title' => 'Tehanu'), $this->user(7));
            $this->assertArrayHasKey('published_year', $error->fields);

            $this->assertCapabilityFails('unauthenticated', 'create_book', array('title' => 'Tehanu'), 'guest');
            $this->assertCapabilityFails('forbidden', 'delete_book', array('id' => 1), $this->user(7, 0));
            $this->assertCapabilityFails('not_found', 'get_book', array('id' => 999999), 'guest');
        }

        public function testALoanIsDueIn14Days(): void
        {
            $this->fake(Clock::class, new class implements Clock {
                public function today(): DateTimeImmutable
                {
                    return new DateTimeImmutable('2026-11-01');
                }
            });
            $book = $this->call('create_book', array('title' => 'Tehanu', 'published_year' => 1990, 'author_id' => $this->author()));

            $loan = $this->call('lend_book', array('book_id' => $book['id'], 'borrower' => 'Ana'), $this->user(7));

            $this->assertSame('2026-11-15', $loan['due_on']);   // 14 days after the fixed today
            $this->assertCapabilityFails('conflict', 'lend_book', array('book_id' => $book['id'], 'borrower' => 'Ben'), $this->user(7));
        }

        public function testTheBookPage(): void
        {
            // the data Route::page gives application/views/Bookshelf/book.pug: get_book and list_authors
            $html = $this->render('Bookshelf/book', array(
                'book' => array('id' => 1, 'title' => 'Tehanu', 'published_year' => 1990, 'summary' => 'The fourth Earthsea book.',
                    'isbn' => null, 'author_id' => 1, 'author' => array('name' => 'Ursula K. Le Guin')),
                'authors' => array(array('id' => 1, 'name' => 'Ursula K. Le Guin'))
            ));

            $this->assertStringContainsString('Tehanu', $html);
            $this->assertStringContainsString('by Ursula K. Le Guin, 1990', $html);
        }
    }
    ```
    `$this->user(7)` is a signed-in user of id 7 and level 0: `delete_book` (level 1) refuses them.
    `$this->call(..., null)` (no third argument) is the command line, with full access.
4. **Run them.**
    ```bash
    docker compose exec dev-box php caligrafer.php test
    ```
    ```text
    PHPUnit 12.5.44 by Sebastian Bergmann and contributors.

    ....                                                                4 / 4 (100%)

    OK (4 tests, 13 assertions)
    ```
    (between them, the PHP version and the time it took). `php caligrafer.php test Loan` runs only the tests whose name matches `Loan` (`testALoanIsDueIn14Days`).

**Check:**
+ `OK (4 tests, 13 assertions)`;
+ the test database has no `Tehanu` afterwards:
  `docker compose exec mysql mysql -uroot -proot caligrafy_test -e "SELECT COUNT(*) FROM books WHERE title = 'Tehanu'"`
  gives `0` (the five sample books of `create_db.sql` stay);
+ break a rule on purpose (remove `required` from `published_year` in `CreateBook`): `testRefusals` fails. Put it back.
## <a name="helpers"></a>Reference

| Helper | What it does |
|---|---|
| `$this->call($capability, $input, $as)` | calls the capability with its checks, validation and audit; returns its answer as plain data |
| `$this->user($id = 1, $level = 0, $attributes = [])` | a signed-in user for `$as`: an id, a permission level (`permissions`), other attributes the capability reads |
| `$this->action($capability, $input, $as)` | calls a capability declared `webOnly: true` as `Route::action` does (2.21.0); returns its answer: a `Caligrafy\Web`, whose `->describe()` gives `type`, `target`, `data`, `status` and `headers`, or plain data |
| `$this->assertCapabilityFails($kind, $capability, $input, $as)` | the capability refuses with `$kind` (`invalid`, `unauthenticated`, `forbidden`, `not_found`, `conflict`); returns the `ServiceError` (`->fields`, `->getMessage()`) |
| `$this->render($view, $data)` | the HTML of a Pug view of `application/views`, as a page shows it |
| `$this->fake($class, $object)` | the [container](https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection) gives `$object` for `$class` in this test |
| `$this->assertQueued($capability, $where = null)` | a [background job](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs) of that capability was pushed in this test (whose input passes the function `$where`); returns its input |

**Who calls (`$as`)**

| `$as` | The test calls as |
|---|---|
| `null` (or nothing) | the command line: full access |
| `'guest'` | a visitor: only public capabilities |
| `$this->user(7)`, an object or an array | that user, over REST |
| a `Caligrafy\Context` | that context (a token: `Context::forToken($row, 'mcp')`) |

**Commands**

| Command | What it does |
|---|---|
| `php caligrafer.php test make <Name>` | writes `tests/<Name>Test.php` (refuses an existing file) |
| `php caligrafer.php test` | runs every `tests/*Test.php` and `tests/*/*Test.php` with PHPUnit; exit 0 when they pass |
| `php caligrafer.php test <filter>` | only the tests whose class or method name matches |

Without PHPUnit it says ` PHPUnit is not installed: composer install (with the development packages), then php caligrafer.php test`.
A warning fails the run (`--fail-on-warning`).
## <a name="database"></a>The database

+ With `DB_ACTIVATE=true`, each test runs in a transaction that is rolled back at its end: the rows a test writes are
  gone after it, and tests never see each other's rows.
+ The settings are those of `.env`, then of `.env.testing` (whose settings win). `DB_TEST_DATABASE=caligrafy_test` in
  `.env` also works: it replaces `DB_DATABASE` for the tests only; the commands that prepare that database still need
  a settings file (`--env`).
+ A test that must not run in a transaction sets `protected $transactions = false;` (and cleans up after itself).
+ Between tests, the container's bindings, the cache's in-memory copies and the counts of the N+1 warning are reset.
## <a name="where"></a>Where tests live

`tests/` at the top of the project, one class per file named `*Test.php`, extending `Caligrafy\Testing\TestCase`.
The production image leaves `tests/` out, and the framework never loads it on a page.
## Common mistakes

+ **A `CREATE`, `ALTER` or `DROP` in a test** (G121): MySQL commits it and ends the test's transaction, so the rows
  of the test stay. Create tables in `create_db.sql` and migrations, before the tests.
+ **Tests on your development database**: they pass or fail with the rows you have. Give them `.env.testing`.
+ **`.env.testing` in git**: it holds your secrets. The project's `.gitignore` leaves out every `.env.*` but
  `.env.example` (2.19.1); a project made before 2.19.1 adds `/.env.*` and `!/.env.example` to its `.gitignore`.
+ **`migrate "" --env .env.testing`**: the empty `""` was needed before 2.19.1. Since 2.19.1, write
  `migrate --env .env.testing`.
+ **A test that reads `$_SESSION` or the request**: a plain capability never does; give the user with `$this->user()`.
+ **`$this->call()` on a web-only capability**: it answers `not_found`, as every other channel. Use `$this->action()`. It
  runs `handle()` without a request: a capability that calls `request()` or signs someone in is tested through its parts, and
  in the browser.
## Related pages

+ [Build once](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#test): capabilities
+ [Dependency injection](https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection#test): fakes
+ [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs#test): `assertQueued()`
+ [Testing Caligrafy](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Caligrafy): the framework's own QA suite
+ [Caligrafer: test](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#test)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Capabilities -->

A capability is the one place where your app's rules live, so it is the first thing to test. A test calls it the way
a page, REST, the JS client or an agent does, with its permission checks, its validation and its audit, as a user, a
visitor, a token or the command line, and checks what it answers or how it refuses. Since 2.18.0.
## With Claude

```text
/caligrafy-quill:new-capability write the tests of create_book: the rule cases as a user, the refusals as a guest
```

Claude runs `php caligrafer.php test make <Name>`, fills `tests/<Name>Test.php` with `$this->call(...)` and
`$this->assertCapabilityFails(...)`, and runs `php caligrafer.php test <Name>`.

**Check** before you say OK:
+ every refusal the capability can give has its assertion (`invalid`, `unauthenticated`, `forbidden`, `not_found`,
  `conflict`);
+ each test creates the rows it needs;
+ `php caligrafer.php test` ends with `OK (...)`.
## By hand

The tests run on a database of their own: set it up once as [The test database](https://github.com/caligrafy/caligrafy-quill/wiki/The-Test-Database)
shows. Then:

```bash
docker compose exec dev-box php caligrafer.php test make Bookshelf
```

and make `tests/BookshelfTest.php` call the capabilities of the Bookshelf (`create_book` needs someone signed in or a
token, `delete_book` has `level: 1`, `get_book` is public):

```php
<?php

use Caligrafy\Database;
use Caligrafy\Testing\TestCase;

final class BookshelfTest extends TestCase
{
    private function author(): int
    {
        // a row for this test only: the test's transaction is rolled back at its end
        return (int) Database::table('authors')->insert(array('name' => 'Ursula K. Le Guin'));
    }

    public function testAReaderAddsABook(): void
    {
        $book = $this->call('create_book', array('title' => 'Tehanu', 'published_year' => 1990, 'author_id' => $this->author()), $this->user(7));

        $this->assertSame('Tehanu', $book['title']);
        $this->assertSame('Ursula K. Le Guin', $book['author']['name']);
    }

    public function testRefusals(): void
    {
        $error = $this->assertCapabilityFails('invalid', 'create_book', array('title' => 'Tehanu'), $this->user(7));
        $this->assertArrayHasKey('published_year', $error->fields);

        $this->assertCapabilityFails('unauthenticated', 'create_book', array('title' => 'Tehanu'), 'guest');
        $this->assertCapabilityFails('forbidden', 'delete_book', array('id' => 1), $this->user(7, 0));
        $this->assertCapabilityFails('not_found', 'get_book', array('id' => 999999), 'guest');
    }
}
```

```bash
docker compose exec dev-box php caligrafer.php test Bookshelf
```

```text
OK (2 tests, 7 assertions)
```

(PHPUnit's header, the PHP version and the time it took are printed too.)
## <a name="as"></a>Who calls: the third argument

`$this->call($capability, $input, $as)` builds the caller from `$as`:

| `$as` | The capability is called by | It may call |
| --- | --- | --- |
| `null`, or nothing | the command line (`Context::cli()`) | everything: full access |
| `'guest'` | a visitor over REST (`Context::guest('rest')`) | only `public: true` capabilities |
| `$this->user(7)` | the user 7 over REST, level 0 | what a signed-in user of that level may call |
| `$this->user(7, 1)` | the user 7, level 1 | also the capabilities with `level: 1` |
| an array or an object | that user (`id`, `permissions` and any attribute the capability reads) | as above |
| a `Caligrafy\Context` | exactly that context | what it allows |

`$this->user($id = 1, $level = 0, $attributes = [])` is a plain object: `id`, the level under
`Context::$levelAttribute` (`permissions` by default), and the attributes you add
(`$this->user(7, 0, ['username' => 'sam@example.com'])`). It is not read from the `users` table.

**As a token.** A token's scopes are checked only when the caller is a token. Create one in the test (it is rolled back
with the rest), then call as it:

```php
use Caligrafy\Context;
use Caligrafy\Tokens;

public function testATokenNeedsItsScope(): void
{
    $readOnly = Tokens::verify(Tokens::create('reports', array('books:read'))['token']);

    $this->assertCapabilityFails('forbidden', 'create_book', array('title' => 'Tehanu', 'published_year' => 1990, 'author_id' => 1), Context::forToken($readOnly, 'mcp'));
}
```

This needs the framework tables in the test database (`platform install --env .env.testing`).
## <a name="refusals"></a>Refusals

`$this->assertCapabilityFails($kind, $capability, $input = [], $as = null)` passes when the capability throws a
`Caligrafy\ServiceError` of that kind, and returns it:

| Kind | Thrown when | Check also |
| --- | --- | --- |
| `invalid` | an input breaks a rule of `$rules`, or `ServiceError::invalid([...])` | `$error->fields`: one message per field |
| `unauthenticated` | nobody is signed in and the capability is not public | |
| `forbidden` | the level or the scope is missing, or `ServiceError::forbidden()` | |
| `not_found` | `ServiceError::notFound()`, or a capability this caller cannot reach (a web-only one) | `$error->getMessage()` |
| `conflict` | `ServiceError::conflict('...')`: the input is valid, the state refuses it | `$error->getMessage()` |

A capability that does not fail makes the test fail with ` <capability> did not fail (expected '<kind>')`; one that
fails with another kind says which: ` <capability> failed with 'forbidden' (...), not 'invalid'`. What each kind becomes on
each channel is in [`Caligrafy\ServiceError`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#serviceerror).
## <a name="fakes"></a>Fakes and background jobs

**A fake.** A capability that asks the [container](https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection)
for a service in its constructor (a clock, a mailer, a payment gateway) gets your object in this test:

```php
$this->fake(Clock::class, new class implements Clock {
    public function today(): DateTimeImmutable
    {
        return new DateTimeImmutable('2026-11-01');
    }
});
$loan = $this->call('lend_book', array('book_id' => $bookId, 'borrower' => 'Ana'), $this->user(7));
$this->assertSame('2026-11-15', $loan['due_on']);
```

The container's bindings are reset before each test, so a fake never leaks into the next one.

**A background job.** `$this->assertQueued($capability, $where = null)` passes when a job of that capability is pending
in `caligrafy_jobs` (pushed in this test, since the table is rolled back), and returns its input:

```php
// a capability whose handle() runs Queue::push('send_welcome_email', ['user_id' => $id]) was called above
$input = $this->assertQueued('send_welcome_email', fn ($input) => $input['user_id'] === 7);
```

The job does not run in the test: call its capability yourself to test what it does
([Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs#test)).
## <a name="reference"></a>Reference

| Helper of `Caligrafy\Testing\TestCase` | What it does |
| --- | --- |
| `$this->call($capability, $input = [], $as = null)` | calls it through `Capabilities::call()`: checks, validation, audit; returns its answer |
| `$this->assertCapabilityFails($kind, $capability, $input = [], $as = null)` | the capability refuses with `$kind`; returns the `ServiceError` |
| `$this->user($id = 1, $level = 0, $attributes = [])` | a signed-in user for `$as` |
| `$this->fake($id, $object)` | the container gives `$object` for `$id` in this test |
| `$this->assertQueued($capability, $where = null)` | a job of the capability is pending; returns its input |
| `$this->action(...)`, `$this->render(...)` | web-only capabilities and views: [Testing pages, forms and actions](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Pages-Forms-and-Actions) |
| `protected $transactions = true` | `false` runs the test without a transaction ([The test database](https://github.com/caligrafy/caligrafy-quill/wiki/The-Test-Database)) |

Before each test, the container is reset and booted, the cache's in-memory copies and the query shapes of the N+1
warning are forgotten. The capability registry itself is in the
[API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capabilities-call).
## Common mistakes

+ **A test that counts on your rows**: it passes or fails with the data you have. Each test creates its rows.
+ **`$this->call()` on a web-only capability**: it answers `not_found`, as every other channel does. Use
  `$this->action()`.
+ **A test that reads `$_SESSION` or the request**: a plain capability never does; give the user with `$this->user()`.
+ **A token without `--user` passes any `level`** (G140): test administrator capabilities with a user of the right level
  and with a token, both.
+ **A custom validator of `config.php`** (G141): the tests, like the command line, do not load
  `application/config/config.php`.
## Related pages

+ [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App)
+ [Testing pages, forms and actions](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Pages-Forms-and-Actions) · [The test database](https://github.com/caligrafy/caligrafy-quill/wiki/The-Test-Database)
+ [Dependency injection](https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection#test)
+ [Caligrafer: test](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer-Job-Commands#test)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Pages-Forms-and-Actions -->

Pages, forms, downloads and web-only actions are thin in Caligrafy: a declared route hands the request to a capability
and renders, redirects or sends what it answers. So a test checks the two parts on their own: the **capability** that
does the work, and the **view** or the **answer** the browser gets. This page shows how, with the helpers that
`Caligrafy\Testing\TestCase` really has. Since 2.18.0 (`action()` since 2.21.0).

> `TestCase` sends no HTTP request: there is no `get('/books')` helper. What a route adds (the sign-in redirect, the CSRF
> check, the flash messages) is the framework's, tested by its own QA suite; check your wiring once in the browser.
## With Claude

```text
/caligrafy-quill:new-capability write the tests of the book page: get_book as a guest, then the view with its data
```

**Check** before you say OK: the test renders the view with the same data the page's `data` option gives it, and
`php caligrafer.php test` ends with `OK (...)`.
## By hand

The database of the tests is set up once: [The test database](https://github.com/caligrafy/caligrafy-quill/wiki/The-Test-Database).
## <a name="page"></a>A page: `Route::page`

```php
Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book', 'authors' => 'list_authors']]);
```

The page calls `get_book` and `list_authors` as the visitor, then renders `application/views/Bookshelf/book.pug` with
`book` and `authors`. Test the same two steps:

```php
public function testTheBookPage(): void
{
    $authorId = (int) Database::table('authors')->insert(array('name' => 'Ursula K. Le Guin'));
    $book = $this->call('create_book', array('title' => 'Tehanu', 'published_year' => 1990, 'author_id' => $authorId));

    $data = array(
        'book' => $this->call('get_book', array('id' => $book['id']), 'guest'),
        'authors' => $this->call('list_authors', array(), 'guest'),
    );
    $html = $this->render('Bookshelf/book', $data);

    $this->assertStringContainsString('Tehanu', $html);
    $this->assertStringContainsString('by Ursula K. Le Guin, 1990', $html);
}
```

+ `$this->render($view, $data)` returns the HTML of `application/views/<view>.pug`, as `View::display()` prints it.
+ On a real page the view also gets `authorized` (`true` when someone is signed in) and `user` (`id`, `username`,
  `permissions`) from the page controller, and the route's variables. A view that reads them needs them in `$data`:
  `$this->render('Bookshelf/book', $data + ['authorized' => false, 'user' => null])`.
## <a name="form"></a>A form: `Route::form`

```php
Route::form('/books', 'create_book', ['success' => '/books/{id}', 'flash' => 'Book added']);
```

`Route::form` gives the capability the form's inputs and the route variables, as the person who sent it. Test the
capability with what the form sends (strings, as a form posts them), as the person who sends it:

```php
private function author(): int
{
    return (int) Database::table('authors')->insert(array('name' => 'Ursula K. Le Guin'));
}

public function testTheBookForm(): void
{
    $book = $this->call('create_book', array('title' => 'Tehanu', 'published_year' => '1990', 'author_id' => (string) $this->author()), $this->user(7));
    $this->assertSame('Tehanu', $book['title']);                 // the form redirects to /books/<this id>

    $error = $this->assertCapabilityFails('invalid', 'create_book', array('title' => ''), $this->user(7));
    $this->assertArrayHasKey('title', $error->fields);           // the form shows it with errors('title')
}
```

What the form then does with the answer, by kind, is the route's: `invalid` and `conflict` go back with `errors()`,
`old()` and `flash('error')`, `unauthenticated` goes to the sign-in page. Test the view's error state with `render()`
and the data the view reads. The options are on
[Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form).
## <a name="download"></a>A download: `Route::download`

`Route::download('/books.csv', 'list_books', ['as' => 'csv'])` sends the result of a read-only capability as a file. The
file is made by public functions of [`Caligrafy\Download`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#download),
so a test can make the same CSV:

```php
use Caligrafy\Download;

public function testTheCatalogExport(): void
{
    $this->call('create_book', array('title' => 'Tehanu', 'published_year' => 1990, 'author_id' => $this->author()));
    $csv = Download::csv(Download::rows($this->call('list_books', array(), 'guest')));

    $this->assertStringContainsString('Tehanu', $csv);   // the header row is the keys of the first row
}
```

`Download::rows()` takes what the capability returns (a list, one row, a page of `paginate()`), `Download::csv()` writes
RFC 4180 lines with CRLF; its arguments are the `bom`, `formulas` and `columns` options of the route.
## <a name="action"></a>A web-only capability: `Route::action`

A capability declared `webOnly: true` answers only `Route::action`: `$this->call()` gets `not_found`, as every other
channel. `$this->action($capability, $input, $as)` calls it as `Route::action` does, and returns what it answered: a
[`Caligrafy\Web`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#web), or plain data.

`open_author_books` of [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#action)
redirects to the book when an author has one, and shows the list otherwise:

```php
public function testAnAuthorWithOneBookOpensIt(): void
{
    $authorId = $this->author();
    $book = $this->call('create_book', array('title' => 'Tehanu', 'published_year' => 1990, 'author_id' => $authorId));

    $answer = $this->action('open_author_books', array('author_id' => $authorId), 'guest')->describe();

    $this->assertSame('redirect', $answer['type']);
    $this->assertSame('/books/' . $book['id'], $answer['target']);
    $this->assertSame(302, $answer['status']);
}
```

`->describe()` gives `type` (`view`, `redirect`, `json` or `text`), `target` (the view, or where a redirect goes),
`data`, `status` and `headers`.
`action()` runs `handle()` without a request: a capability that calls `request()`, reads the session or signs someone
in is tested through the plain capabilities it calls, and in the browser.
## <a name="snap"></a>Snap Cards and the assistant

Snap's capabilities are capabilities: the tables must be in the test database (`platform install` on it). The
assistant's planner is faked with `Caligrafy\Snap\Planner::$transport`, a function that gets the request and returns
the model's answer:

```php
Caligrafy\Snap\Planner::$transport = function (array $request) {
    return (object) array('stopReason' => 'tool_use', 'content' => array((object) array('type' => 'tool_use', 'id' => 't1',
        'name' => 'show_cards', 'input' => array('caption' => 'Here it is.', 'cards' => array(array('capability' => 'list_books'))))));
};
$answer = $this->action('snap_ask', array('text' => 'show me the catalog'), $this->user(1))->describe()['data'];
```

The designed cards have their own, `Caligrafy\Snap\Designer::$transport`, or keep to the rules with
`Caligrafy\Snap\Designer::$model = false` (2.24.1). See
[Snap Cards and the assistant](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant#test).
## Common mistakes

+ **Testing the HTML of a whole page for a rule**: the rule is in the capability. Assert it there; keep `render()` for
  what the view shows.
+ **A view that reads `user` or `authorized` fails in a test**: give them in `$data`, as the page controller does.
+ **`$this->call()` on a web-only capability**: `not_found`. Use `$this->action()`.
+ **Form values as numbers**: a form sends strings. Test with strings when the rules must accept them.
## Related pages

+ [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App)
+ [Testing capabilities](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Capabilities) · [The test database](https://github.com/caligrafy/caligrafy-quill/wiki/The-Test-Database)
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes)
+ [API reference: controllers and views](https://github.com/caligrafy/caligrafy-quill/wiki/API-Pages)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/The-Test-Database -->

The tests of an app run on a **database of their own**, and each test runs in a **transaction that is rolled back** at
its end: the rows a test writes are gone after it, and tests never see each other's rows or yours. This page sets that
database up, and says what the test bootstrap does with the settings. Since 2.18.0.
## With Claude

```text
/caligrafy-quill:db create the test database: caligrafy_test, with the framework tables, my tables and the migrations
```

**Check** before you say OK: `php caligrafer.php migrate status --env .env.testing` lists every migration as `ran`, and
`php caligrafer.php test` passes twice in a row.
## By hand

Run the commands in the Docker server (`docker compose exec dev-box ...`; without Docker, drop it and use your MySQL).

1. **Its settings.** Copy `.env` and change one line:
    ```bash
    cp .env .env.testing
    ```
    ```text
    DB_DATABASE=caligrafy_test
    ```
    `.env.testing` holds the same secrets as `.env`: the project's `.gitignore` leaves out every `.env.*` file but
    `.env.example` (2.19.1).
2. **The database and its tables.**
    ```bash
    docker compose exec mysql mysql -uroot -proot -e "CREATE DATABASE IF NOT EXISTS caligrafy_test"
    docker compose exec dev-box php caligrafer.php platform install --env .env.testing
    docker compose exec dev-box php caligrafer.php sql application/models/Bookshelf/create_db.sql --env .env.testing
    docker compose exec dev-box php caligrafer.php migrate --env .env.testing
    ```
    ```text
     application/models/Bookshelf/create_db.sql run on caligrafy_test
     1 migration(s) run on caligrafy_test
    ```
    Run `sql` for each `application/models/<folder>/create_db.sql` of the app.
3. **Run the tests.**
    ```bash
    docker compose exec dev-box php caligrafer.php test
    ```

**Check:** after the tests, the rows they wrote are not in the test database:
`docker compose exec mysql mysql -uroot -proot caligrafy_test -e "SELECT COUNT(*) FROM books WHERE title = 'Tehanu'"`
gives `0`.

After every new migration, run `migrate --env .env.testing` again: the tests use the tables as they are.
## <a name="settings"></a>Which settings the tests read

`php caligrafer.php test` runs PHPUnit with `framework/testing/bootstrap.php`, which:

1. loads `vendor/autoload.php`;
2. reads `.env`, then `.env.testing` when it exists: its settings win;
3. when `DB_TEST_DATABASE` is set (and not empty), puts it in place of `DB_DATABASE` for the tests;
4. sets `CALIGRAFY_TESTING=true`;
5. loads the framework as the command line does (`Caligrafer::run()`: the settings as constants, the helpers, the class
   map; not `application/config/config.php`), then `Caligrafy\Testing\TestCase`.

So there are two ways to point the tests at their database:

| Way | Where | For the commands that prepare it |
| --- | --- | --- |
| `.env.testing` with its own `DB_DATABASE` (and any other setting) | a file next to `.env` | `--env .env.testing` |
| `DB_TEST_DATABASE=caligrafy_test` | one line in `.env` | still a settings file: the commands read `DB_DATABASE`, so `--env` with a file that names it |
## <a name="transactions"></a>The transaction of each test

With `DB_ACTIVATE=true`, before each test `TestCase` opens a transaction on the connection, and after it rolls it back.
Also before each test: the container is reset and booted, the cache's in-memory copies are cleared, and the query
shapes the N+1 warning counts are forgotten.

+ **A `CREATE`, `ALTER` or `DROP`** in a test ends the transaction: MySQL commits it at once (G121), and the rows the test
  wrote before stay. Create tables in `create_db.sql` and migrations, before the tests.
+ **A test without a transaction**: `protected $transactions = false;` in the class. It then cleans up after itself.
+ **The cache store** `database` (`caligrafy_cache`) is in the same transaction: values a test puts there are rolled back
  too.
## Common mistakes

+ **Tests on your development database**: without `.env.testing` or `DB_TEST_DATABASE`, the tests run on the database
  of `.env`. The transactions keep its rows, but the tests pass or fail with what is there.
+ **The test database is behind**: a new migration ran on the development database only, and a test fails on a
  missing column. `migrate --env .env.testing`.
+ **`migrate "" --env .env.testing`**: the empty word was needed before 2.19.1.
+ **`.env.testing` in git**: a project made before 2.19.1 adds `/.env.*` and `!/.env.example` to its `.gitignore`.
+ **Snap or token tests fail on a missing table**: `platform install --env .env.testing` creates the framework tables
  (tokens, audit, jobs, cache, migrations, Snap) in the test database.
## Related pages

+ [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App)
+ [Testing capabilities](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Capabilities) · [Testing pages, forms and actions](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Pages-Forms-and-Actions)
+ [Migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations)
+ [Caligrafer: data commands](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer-Data-Commands)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection -->

**Dependency injection** means a class asks for what it uses in its constructor instead of creating it, and
Caligrafy's **container** gives it. A capability then stays short, the real thing (a clock, a mailer, a payment
gateway) is chosen in one file, and a test can swap it for a fake. Since 2.18.0.
## With Claude

Say what the capability uses from outside, and that a test must be able to replace it:

```text
/caligrafy-quill:new-capability lend_book loans:write: lend a book for a number of days (14 by default) from today; take the date from a Clock so a test can fix it
```

Claude gives the capability a constructor (`public function __construct(private Clock $clock) {}`), binds the
interface in `application/config/container.php`, and writes a test that replaces it with `$this->fake()`.

**Check** before you say OK:
+ `handle()` never writes `new SystemClock()` (or `new` of anything with settings): it uses what the constructor got;
+ every interface the constructor asks for is bound in `application/config/container.php`;
+ `php caligrafer.php call lend_book book_id=2 borrower=Dan` works, and `php caligrafer.php test` passes.
## <a name="ask"></a>By hand

A loan is due a number of days after today, 14 by default (`lend_book` of the course, with a clock). "Today" comes
from a `Clock`, so a test can choose the date. Run the commands in
the Docker container (`docker compose exec dev-box php caligrafer.php ...`; without Docker, drop
`docker compose exec dev-box`).

1. **The interface.** Create `application/support/Clock.php`:
    ```php
    <?php

    // What time it is: the capabilities ask for a Clock, so a test can give them a fixed one
    interface Clock
    {
        public function today(): DateTimeImmutable;
    }
    ```
2. **The real one.** Create `application/support/SystemClock.php`:
    ```php
    <?php

    // The real clock: today, in the time zone of the application (SERVER_TIMEZONE)
    class SystemClock implements Clock
    {
        public function today(): DateTimeImmutable
        {
            return new DateTimeImmutable('today');
        }
    }
    ```
    Any folder of `application/` but `config/` and `views/` is found by the class map: no `require` to write.
3. **<a name="bind"></a>The binding.** Create `application/config/container.php`:
    ```php
    <?php

    use Caligrafy\Container;

    // What the container gives a class that asks for an interface (or for a class that needs settings)
    Container::bind(Clock::class, SystemClock::class);
    ```
4. **The capability asks for it.** `lend_book` is the capability of the course's loans
   ([lesson 13](https://github.com/caligrafy/caligrafy-quill-course/wiki/13-Capstone-Loans): the `loans` table and the
   `Loan` model). Without it, run
   `docker compose exec dev-box php caligrafer.php service Loans/LendBook --scope loans:write`. Then make
   `application/services/Loans/LendBook.php` read (the course's, with the date from the clock):
    ```php
    <?php

    use Caligrafy\Capability;
    use Caligrafy\Context;
    use Caligrafy\Service;
    use Caligrafy\ServiceError;

    // lend_book: records that someone borrowed a book, for a number of days counted from the Clock's today
    #[Capability(
        name: 'lend_book',
        description: 'Lends a book of the catalog to someone for a number of days (14 by default) and returns the loan. Refused when the book is already lent.',
        scope: 'loans:write'
    )]
    class LendBook extends Service
    {
        public $rules = array('book_id' => 'required|integer', 'borrower' => 'required|max_len,100', 'days' => 'integer|min_numeric,1|max_numeric,60');
        public $filters = array('borrower' => 'trim');
        public $descriptions = array(
            'book_id' => 'The id of the book (list_books)',
            'borrower' => 'The name of the person who borrows it',
            'days' => 'For how many days: 1 to 60, 14 by default'
        );

        // the container gives the Clock bound in application/config/container.php
        public function __construct(private Clock $clock)
        {
        }

        public function handle(array $input, Context $context)
        {
            if (!Book::find($input['book_id'])) {
                throw ServiceError::notFound("There is no book #{$input['book_id']}");
            }
            $open = Loan::where('book_id', $input['book_id'])->whereNull('returned_at')->first();
            if ($open) {
                throw ServiceError::conflict("This book is already lent to {$open->borrower}");
            }
            $days = (int) ($input['days'] ?? 14);
            $id = Loan::insert(array(
                'book_id' => $input['book_id'],
                'borrower' => $input['borrower'],
                'due_on' => $this->clock->today()->modify("+$days days")->format('Y-m-d')
            ));
            return Loan::find($id);
        }
    }
    ```
5. **Run it.** `docker compose exec dev-box php caligrafer.php call lend_book book_id=2 borrower=Dan` returns the loan
   with `"due_on"` 14 days from today (`"2026-11-21"` on 7 November 2026). Run it again: the book is out,
   `{"error": {"code": "conflict", "message": "This book is already lent to Dan"}}`.
6. **In a test, a fixed clock.** See step 3 of [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App#first):
    ```php
    $this->fake(Clock::class, new class implements Clock {
        public function today(): DateTimeImmutable
        {
            return new DateTimeImmutable('2026-11-01');
        }
    });
    $loan = $this->call('lend_book', ['book_id' => $bookId, 'borrower' => 'Ana'], $this->user(7));
    $this->assertSame('2026-11-15', $loan['due_on']);   // 14 days after the fixed today
    ```

**Check:**
+ `call lend_book` works with the binding;
+ remove `application/config/container.php` for a moment: `call lend_book ...` then says
  `The container cannot build Clock: it is an interface. Bind it to a class in application/config/container.php`.
  Put it back.
## Reference

Every capability is built by the container, with what its constructor asks for. A class type in a constructor is
built the same way, with what its own constructor asks for; a parameter with a default keeps it.

| Method (in `application/config/container.php`) | What it does |
|---|---|
| `Container::bind($id, $factory)` | a new object each time; `$factory` is a class name or a function that returns the object |
| `Container::singleton($id, $factory)` | one object for the whole request, made the first time it is asked for |
| `Container::instance($id, $object)` | this object |

```php
Container::bind(Clock::class, SystemClock::class);                                               // an interface -> a class
Container::singleton(PaymentGateway::class, fn () => new StripeGateway(getenv('PAY_PRIVATE_KEY_TEST')));   // your own class, with settings
```

| Method (anywhere) | What it does |
|---|---|
| `Container::get($id)` | the object for `$id`: its instance, its binding, or the class built with what it asks for |
| `Container::make($class, ['name' => $value])` | a new `$class` (never a shared one), some constructor parameters given by name |
| `Container::has($id)` | whether `$id` has a binding or an instance |
| `Container::reset()` | forgets every binding and instance (the tests do it between tests) |

How a constructor parameter is given: by name from `make()`'s parameters, else by its class or interface type, else
its default, else `null` when it accepts `null`. The file `application/config/container.php` is read once: by the web
front controller after `config.php`, by the command line and the tests the first time the container is used.

**What it says when it cannot build a class:**

| Cause | Message |
|---|---|
| an interface with no binding | `The container cannot build Clock: it is an interface. Bind it to a class in application/config/container.php` |
| a parameter with no type and no default | `The container cannot build NeedsName: nothing gives its parameter $name. Give it a default, a class type, or bind it in application/config/container.php` |
| a class that needs itself | `The container cannot build A: it needs itself (A -> B -> A)` |
| an abstract class, or a constructor that is not public | `The container cannot build X: it is abstract or its constructor is not public` |

Over REST the call answers 500, over MCP a JSON-RPC `Internal error` (-32603); the audit log records `error  LogicException`.
## <a name="test"></a>In tests

`$this->fake(Clock::class, $object)` gives `$object` to every class that asks for `Clock`, for this test only: the
container is reset before and after each test, and the bindings of `application/config/container.php` are read
again first, so the fake replaces them. See [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App#helpers).
## Common mistakes

+ **`new` in `handle()`** for something with settings or side effects (a mailer, a payment client): a test cannot
  replace it. Ask for it in the constructor.
+ **An interface with no binding**: the capability fails at its first call. Bind it in `application/config/container.php`.
+ **A binding written in `web.php`**: the command line, the queue and the tests never read `web.php`. Write bindings in
  `application/config/container.php`.
## Related pages

+ [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App): `$this->fake()`
+ [Build once](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#service): capabilities
+ [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs): jobs are capabilities too, built the same way


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation -->

# Validation

Validation checks that an input follows the rules the application expects before any code uses it; filtering cleans
an input (trims it, lowers its case) before the check. In Caligrafy both are written once, in the `$rules` and
`$filters` of a capability. The framework applies them on every call: a form (`Route::form`), the REST API, a Vue app,
the command line and AI agents all get the same message for each field. The rules also become the JSON Schema that
agents and the JS client see. The rules are those of [GUMP](https://github.com/Wixel/GUMP) 2.3 (the validation
library Caligrafy uses), plus Caligrafy's own: `exists`, `unique`, `current_year` and the file rules.

## With Claude

```text
/caligrafy-quill:new-capability create_book books:write
"The title is required, 200 characters at most, trimmed. The year is a whole number from 1450 to this year.
The author must exist."
```

Claude writes the `$rules`, `$filters` and `$descriptions` of the capability in `application/services/<Folder>/`.

**Check**

- [ ] Every input `handle()` reads is in `$rules` (`''` when it has no rule): the others never reach it.
- [ ] Mandatory inputs have `required`; a mandatory file input has `required|file` (or `required_file`, 2.19.1).
- [ ] A foreign key has `exists,<table>.id`; a value that must be unique has `unique,<table>.<column>` and the
      column keeps its `UNIQUE` index.
- [ ] `php caligrafer.php call <name>` with a wrong input answers `invalid` with a message per field.

## By hand

Before you start: the Bookshelf tables of
[Routing, step 1](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing#definingroutes).

1. **Write the rules.** Run `docker compose exec dev-box php caligrafer.php service Bookshelf/CreateBook --scope books:write` and replace the
   content of `application/services/Bookshelf/CreateBook.php` with:

   ```php
   <?php

   use Caligrafy\Capability;
   use Caligrafy\Context;
   use Caligrafy\Service;

   #[Capability(
       name: 'create_book',
       description: 'Adds a book to the Bookshelf catalog and returns it with its id and its author. The author must already exist: use list_authors to find author_id.',
       scope: 'books:write'
   )]
   class CreateBook extends Service
   {
       public $rules = array(
           'title' => 'required|max_len,200',
           'published_year' => 'required|integer|min_numeric,1450|max_numeric,current_year',
           'summary' => 'max_len,2000',
           'author_id' => 'required|integer|exists,authors.id'
       );
       public $filters = array('title' => 'trim', 'summary' => 'trim');
       public $descriptions = array(
           'title' => 'The title of the book',
           'published_year' => 'The year it was first published, for example 1969 (not after this year)',
           'summary' => 'Optional: one or two sentences about the book',
           'author_id' => 'The id of its author (list_authors)'
       );

       public function handle(array $input, Context $context)
       {
           $id = Book::insert($input);   // one INSERT, every value bound; returns the id of the new book
           return Book::with('author')->find($id);
       }
   }
   ```

   (`Book` is the model of [Routing, step 2](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing#definingroutes).)

2. **Send wrong inputs.** Run:

   ```bash
   docker compose exec dev-box php caligrafer.php call create_book title= published_year=2999 author_id=9
   ```

   It prints (the year is the year of today):

   ```json
   {
       "error": {
           "code": "invalid",
           "message": "Some of the inputs are invalid",
           "fields": {
               "title": "The Title field is required",
               "published_year": "The Published Year field needs to be a numeric value, equal to, or lower than 2026",
               "author_id": "There is no such author"
           }
       }
   }
   ```

   The same `fields` come back to a form (`errors('title')`), to REST (`422`) and to an agent (`isError: true`).

3. **Send good ones.** Run `docker compose exec dev-box php caligrafer.php call create_book "title=  Dawn " published_year=1987 author_id=2`.
   It prints `{"data": {"id": 6, "title": "Dawn", ..., "author": {"id": 2, "name": "Octavia E. Butler", ...}}}`: the
   `trim` filter removed the spaces before the check.

4. **See what agents see.** Run `docker compose exec dev-box php caligrafer.php capabilities --json`. The `input` of `create_book` is:

   ```json
   {
       "type": "object",
       "properties": {
           "title": {"type": "string", "maxLength": 200, "description": "The title of the book"},
           "published_year": {"type": "integer", "minimum": 1450, "maximum": 2026, "description": "The year it was first published, for example 1969 (not after this year)"},
           "summary": {"type": "string", "maxLength": 2000, "description": "Optional: one or two sentences about the book"},
           "author_id": {"type": "integer", "description": "The id of its author (list_authors)"}
       },
       "additionalProperties": false,
       "required": ["title", "published_year", "author_id"]
   }
   ```

**Check**

- [ ] Each wrong field has its own message; a right field has none.
- [ ] The schema lists every input, with `required` for the mandatory ones.

## <a name="validation"></a>How the rules are applied

+ **Syntax**: rules are separated by `|`, a rule's argument follows a `,`, and a list inside an argument uses `;`:
  `'cover' => 'required|file|extension,png;jpg|max_size,2mb'`.
+ **Order**: the filters run first, then the rules. Each field stops at its first broken rule, so a field has one
  message.
+ **Empty inputs**: a field with neither `required` nor `required_file` is not checked when it is empty or missing:
  `'summary' => 'max_len,2000'` accepts no summary. Add `required` when the value must be there.
+ **Only declared inputs**: only the keys of `$rules` reach `handle()`; an input with no rule is declared with `''`.
+ **Values stay strings**: a rule checks a value, it does not convert it. `integer` accepts `"5"` and `handle()`
  gets `"5"`.
+ **An unknown rule name** stops the call with an error (`'x' validator does not exist`).
+ **Messages** are GUMP's English messages, built from the field name (`published_year` -> "Published Year").
  `exists` and `unique` name the table or the column.

## <a name="database-rules"></a>Rules of the framework

| Rule | What it checks | Message | In the JSON Schema |
| --- | --- | --- | --- |
| `exists,<table>.<column>` | the value is in that column: a foreign key that points at a real row | "There is no such author" (the table in the singular) | nothing added |
| `unique,<table>.<column>` | no row has the value yet | "This name is already used" (the column) | nothing added |
| `unique,<table>.<column>,<ignoreColumn>,<ignoreField>` | the same, leaving out the row whose `<ignoreColumn>` equals the input `<ignoreField>` (an update); `<ignoreField>` defaults to `<ignoreColumn>` | the same | nothing added |
| `min_numeric,current_year`, `max_numeric,current_year` | the year of today, read when the input is checked | GUMP's `min_numeric` / `max_numeric` message with the year | `minimum` / `maximum`: this year |
| `file` | a file input ([below](#filevalidation)) | | `"description": "The URL or the path of a file"` |
| `extension,<a>;<b>` (with `file`) | the file's type is in the list | "This type of file is not accepted: png, jpg, webp" | nothing added |
| `max_size,<size>` (with `file`) | the file is at most that size: bytes, or `kb`, `mb`, `gb` (`500kb`, `1.5mb`) | "The file is too large (at most 2 MB)" | nothing added |
| `required_file` | in a capability, a file input that must be sent, like `required\|file` (2.19.1; before, it did not make the file required) | "The Cover field needs a file" | listed in `required`, `"description": "The URL or the path of a file"` |

```php
public $rules = array(
    'author_id'      => 'required|integer|exists,authors.id',
    'name'           => 'required|max_len,150|unique,authors.name',
    'published_year' => 'required|integer|min_numeric,1450|max_numeric,current_year',
);

// an update: the author being changed does not count as a duplicate of itself
public $rules = array('id' => 'required|integer', 'name' => 'required|max_len,150|unique,authors.name,id,id');
```

+ `exists` and `unique` run one bound query through the query builder, on the app's database (in tests, the test
  database). The table and the column are checked as the builder checks names (letters, digits and `_`, one optional
  `db.` prefix): a wrong name stops with an error and is never sent to the database.
+ They are checks, not constraints: two sign-ups at the same instant can both pass `unique`. Keep the column's
  `UNIQUE` index and catch the duplicate.
+ A rule named `exists` or `unique` that your app added with `GUMP::add_validator()` before the first validation is
  kept instead of the framework's.
+ `GUMP::set_error_message('exists', '...')` replaces their message for every field.

## <a name="rules"></a>Every rule

GUMP 2.3.2 (the version in `composer.lock`), checked in `vendor/wixel/gump/gump.class.php`. "Schema" is what
`Capabilities::schemaFromRules()` adds to the input's JSON Schema; every input is `"type": "string"` unless a rule
says otherwise, and `required` lists it in `required`. On a non-string type, `format`, `minLength` and `maxLength`
are left out; on a string, `minimum` and `maximum` are.

**Presence and type**

| Rule | Passes when the value | Schema |
| --- | --- | --- |
| `required` | exists and is not empty (not `null`, `''` or `[]`) | listed in `required` |
| `integer` | is an integer | `"type": "integer"` |
| `numeric` | is a number or a numeric string | `"type": "number"` |
| `float` | is a number with a decimal point | `"type": "number"` |
| `boolean` | is yes/no, on/off, 1/0 or true/false; `boolean,strict`: only true/false | `"type": "boolean"` |
| `valid_json_string` | is valid JSON | |
| `valid_array_size_greater,n`, `valid_array_size_lesser,n`, `valid_array_size_equal,n` | is an array with at least, at most, exactly `n` items | |

**Length and numbers**

| Rule | Passes when the value | Schema |
| --- | --- | --- |
| `max_len,n` | has at most `n` characters | `maxLength` |
| `min_len,n` | has at least `n` characters | `minLength` |
| `exact_len,n` | has exactly `n` characters | `minLength` and `maxLength` |
| `between_len,min;max` | has `min` to `max` characters | |
| `min_numeric,n` | is a number `>= n` (`current_year` allowed) | `minimum` |
| `max_numeric,n` | is a number `<= n` (`current_year` allowed) | `maximum` |
| `even`, `odd`, `prime` | is an even, odd, prime number | |
| `word_count,min;3;max;5` | has 3 to 5 words. Write the `;` form: with commas (`word_count,min,3,max,5`) the numbers are dropped and every value passes | |

**Text and characters**

| Rule | Passes when the value |
| --- | --- |
| `alpha` | has only letters |
| `alpha_numeric` | has only letters and digits |
| `alpha_dash` | has only letters, `-` and `_` |
| `alpha_numeric_dash` | has only letters, digits, `-` and `_` |
| `alpha_space` | has only letters and spaces |
| `alpha_numeric_space` | has only letters, digits and spaces |
| `valid_name` | looks like a person's name |
| `street_address` | looks like a street address |
| `starts,x` | starts with `x` |
| `regex,/pattern/` | matches the regular expression |
| `camel_case`, `snake_case`, `url_slug` | is in that format |
| `strong_password` | has 8 characters or more with an upper case letter, a lower case letter, a digit and a special character |
| `no_sql_injection`, `no_xss` | has none of the common SQL injection or script patterns (a filter of last resort: bind values and escape output anyway) |

**Lists and other fields**

| Rule | Passes when the value | Schema |
| --- | --- | --- |
| `contains,red;green` | is one of the values (the message lists them) | |
| `contains_list,red;green` | is one of the values (the message does not list them) | `enum: ["red", "green"]` |
| `doesnt_contain_list,red;green` | is none of the values | |
| `equalsfield,other` | equals the input `other` (a password confirmation) | |

**Formats**

| Rule | Passes when the value is | Schema |
| --- | --- | --- |
| `valid_email` | an email address | `"format": "email"` |
| `valid_url` | a URL | `"format": "uri"` |
| `url_exists` | a URL that answers (a network call at validation) | |
| `uuid` | a UUID, any version | `"format": "uuid"` |
| `guidv4` | a version 4 GUID | |
| `valid_ip`, `valid_ipv4`, `valid_ipv6` | an IP address | |
| `domain_name` | a domain name without a protocol | |
| `port_number` | a port, 1 to 65535 | |
| `mac_address` | a MAC address | |
| `valid_cc` | a credit card number (Luhn check) | |
| `iban` | an IBAN | |
| `phone_number` | a phone number such as `555-555-5555` or `1 (519) 555-4422` | |
| `postal_code,US` | a postal code of that country | |
| `country_code`, `language_code`, `currency_code` | an ISO 3166, ISO 639 or ISO 4217 code | |
| `timezone` | a timezone identifier (`Europe/Paris`) | |
| `hex_color`, `rgb_color` | a color | |
| `base64`, `jwt_token` | base64 data, a JWT | |
| `hash,md5` | a hash of that algorithm | |
| `social_handle` | a social media handle | |
| `latitude`, `longitude`, `coordinates` | a coordinate, or `lat,lng` | |

**Dates and times**

| Rule | Passes when the value is | Schema |
| --- | --- | --- |
| `date` | a date (ISO 8601); `date,d/m/Y` with that format | `"format": "date"` (also with a custom format) |
| `min_age,18` | a date of birth (`Y-m-d`) at least 18 years ago | |
| `future_date`, `past_date` | after, before now | |
| `business_day` | a Monday to Friday | |
| `valid_time` | `HH:MM` or `HH:MM:SS` | |
| `date_range,2024-01-01;2024-12-31` | between the two dates | |

**Uploaded files with GUMP** (in the `check()` of a controller you keep, on `$_FILES`; in a capability, use [the `file` rule](#filevalidation))

| Rule | Passes when |
| --- | --- |
| `required_file` | a file was uploaded in that field |
| `extension,png;jpg` | the uploaded file's name ends with one of the extensions (the type is not checked) |

## <a name="filter"></a>Filters

Filters change an input before the rules run. Write them in `$filters`, separated by `|`:
`public $filters = array('title' => 'trim', 'email' => 'trim|lower_case');`. Only filters of declared inputs run.

| Filter | What it does |
| --- | --- |
| `trim` | removes spaces at the start and the end |
| `lower_case`, `upper_case` | changes the case |
| `slug` | makes a URL slug (`Dune Messiah` -> `dune-messiah`) |
| `sanitize_string` | removes script tags and encodes HTML |
| `htmlencode`, `urlencode` | encodes HTML entities, URL characters |
| `sanitize_email`, `sanitize_numbers`, `sanitize_floats` | removes characters that cannot be in an email, a number, a decimal number |
| `whole_number` | turns a number into a whole number |
| `boolean` | `1`, `true`, `yes`, `on` become `true`, anything else `false` |
| `basic_tags` | removes every HTML tag but basic text tags |
| `rmpunctuation` | removes punctuation |
| `noise_words` | removes noise words (and, the, of...) |
| `ms_word_characters` | turns Word's curly quotes, dashes and ellipses into plain characters |
| any PHP function of one value | `base64_encode`, `json_decode`, `strtolower`... (`function_exists()`); an unknown name stops with an error |

## <a name="validationandfiltering"></a>Other ways: validating in a controller

A controller in older code ([Controllers](https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers#when))
can validate data itself. The framework's rules work there too. These checks are for the web only: a capability is
the place for rules that every channel must follow.

```php
<?php

use Caligrafy\Controller;

class CheckController extends Controller
{
    public function show()
    {
        $input = array('username' => '  ada lovelace ', 'password' => '123');
        $rules = array('username' => 'required|alpha_numeric', 'password' => 'required|max_len,100|min_len,6');

        $errors = $this->validate($input, $rules);
        // ['username' => 'The Username field may only contain letters and numbers',
        //  'password' => 'The Password field needs to be at least 6 characters']

        $clean = $this->filter($input, array('username' => 'trim|lower_case'));
        // ['username' => 'ada lovelace', 'password' => '123']

        return api(array('errors' => $errors, 'clean' => $clean));
    }
}
```

| Method | Returns |
| --- | --- |
| `$this->validate($data, $rules)` | `true`, or `['field' => 'message']` |
| `$this->filter($data, $filters)` | the filtered data |
| `$this->check($data, $rules)` | as `validate()` |
| `$this->check($data, [], $filters)` | as `filter()` |
| `$this->check($data, $rules, $filters)` | the **filtered data** when valid, the **errors** when not: both are arrays, so `!== true` cannot tell them apart. Filter, then validate |
| `$this->validator->is_valid($data, $rules, $messages)` | `true`, or a list of readable messages (with HTML); `$messages` is `['username' => ['alpha_numeric' => 'Letters and digits only']]` |

Your own rule, for capabilities and controllers alike: write it in a file of its own under `application/`, for
example `application/rules/isbn.php`. The class map runs a file with top-level code at start, for web requests and for
the command line alike (`application/config/config.php` is not read by `php caligrafer.php call`, so a rule added
there is unknown to the command line). Use it as `'isbn' => 'required|isbn'`; the schema adds nothing for it.

```php
<?php
// application/rules/isbn.php
GUMP::add_validator('isbn', function ($field, array $input, array $params = [], $value = null) {
    return (bool) preg_match('/^(97[89])?\d{9}[\dX]$/', str_replace('-', '', (string) $value));
}, 'The {field} field must be an ISBN');
```

## <a name="filevalidation"></a>File validation

**In a capability**: the `file` rule, with an allow-list and a size.

```php
public $rules = array('cover' => 'required|file|extension,png;jpg;webp|max_size,2mb');
```

+ Web pages (`Route::form`) and REST (`Route::capability`, `Route::capabilities`) check the uploaded file (one file,
  the allow-list, the size), save it in `public/uploads/` under a random name once the caller is allowed, and give
  `handle()` its URL. A text sent in that field is dropped. When the capability fails, the file is deleted.
+ AI agents (MCP) and the command line send a URL or a path: its extension is checked.
+ Without `extension`, the default list of `uploadFile()` applies; scripts and markup (`php`, `html`, `js`, `svg`...)
  are always refused.
+ GUMP never sees `file`, `extension`, `max_size` or `required_file` in a capability: Caligrafy handles them.
  `required|file` and `required_file` (2.19.1) make the file required on every channel: no file, URL or path answers
  `"cover": "The Cover field needs a file"`, and the JSON Schema lists the input in `required`. Before 2.19.1,
  `required_file` alone left the file optional.
+ The complete example: [Declarative routes: file inputs](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#files).

**In a controller** (other ways): check `$_FILES` with GUMP's file rules, then save with `uploadFile()`:

```php
$result = $this->check($_FILES, array('image' => 'required_file|extension,png;jpg'));
if ($result === true) {
    $url = uploadFile($this->request->files('image'), array('png', 'jpg'));   // '' when refused
}
```

## Common mistakes

+ **No `required`**: an empty input passes every other rule.
+ **`required_file` in a capability before 2.19.1**: the file was optional. Write `required|file`, which works on every
  version.
+ **`word_count,min,3,max,5`**: the commas drop the numbers and every value passes. Write `word_count,min;3;max;5`.
+ **An input `handle()` reads but `$rules` does not list**: it never arrives. Declare it with `''`.
+ **`unique` without the `UNIQUE` index**: two requests at the same instant can both pass.
+ **`date,d/m/Y` and agents**: the schema still says `"format": "date"` (ISO). Describe the format in `$descriptions`.
+ **`check()` with rules and filters, tested with `!== true`**: the filtered data is an array too.
+ **Appending `date('Y')` to a rule**: write `max_numeric,current_year`; the rules are read by the schema as written.

## Related pages

+ [Build once: write a capability](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#service)
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes): forms that show these messages
+ [Views: forms](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#formhelpers): `errors()`, `old()`
+ [GUMP](https://github.com/Wixel/GUMP)

<br /><br />
>[Next Section: Learn about Views](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views -->

A **view** is the HTML page a person sees. In Caligrafy a view is a [Pug](https://pugjs.org) file in `application/views/`, rendered on the server by Phug (Pug for PHP). A page route names the view and the capabilities that give it its data (`Route::page`); a form posts to a capability (`Route::form`) and comes back to the page with its errors. Every page is built from Caligrafy's [page components](#pagecomponents): a top bar, a title band, forms, rows and tiles, with no CSS to write, at every screen size.
## With Claude

With the [Claude Code plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin), ask for the page together with the feature it shows:

```text
/caligrafy-quill:new-capability books: a list of the books (title, author), a page for one book, and a form to add one
```

Claude writes the capabilities in `application/services/Bookshelf/`, the page routes and the form route in `application/config/routing/web.php` (`Route::page` with `data`, `Route::form`), and the views in `application/views/Bookshelf/`, built on the master `default/master/site` with the page components of [ui-guidelines](https://github.com/caligrafy/caligrafy-quill/tree/master/claude-plugin/skills/caligrafy/reference/ui-guidelines.md). To change only how pages look, use [design styles](https://github.com/caligrafy/caligrafy-quill/wiki/Design-Styles) (`/caligrafy-quill:design`).

**Check** before you say OK:
+ Open the list page and one item's page in the browser, at desktop and phone width.
+ Send the form empty: each field shows its own message under it, and what you typed is still there.
+ Send it filled: you land on the new item's page with the success message, once.
+ The views extend `../default/master/site`, join strings with `.` (never `+`), and every `form` has `method='POST'` and `=csrf()`.
+ `web.php` has no closure that returns a view, and no controller that only passes data to a view.
## <a name="viewsstartup"></a>By hand

You build the Bookshelf pages: the catalog with an add form at `/books`, and one page per book at `/books/<id>`. Commands run in the project folder with the Docker server of the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart); addresses start with `http://localhost:8080/`. If you followed the [course](https://github.com/caligrafy/caligrafy-quill-course/wiki) or [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability), the files of steps 1 to 3 are already there: check that they match and go to step 4.

**1. The tables.** Write `application/models/Bookshelf/create_db.sql` (the same file as [Routing, step 1](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing#definingroutes)):
```sql
/* Bookshelf: the first version of its tables, and sample books.
 * Run it with: docker compose exec dev-box php caligrafer.php sql application/models/Bookshelf/create_db.sql
 * Safe to run again: CREATE TABLE IF NOT EXISTS skips a table that exists, INSERT IGNORE a row whose id exists.
 */

CREATE TABLE IF NOT EXISTS authors (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    name VARCHAR(150) NOT NULL,
    bio TEXT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;

CREATE TABLE IF NOT EXISTS books (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    title VARCHAR(200) NOT NULL,
    published_year SMALLINT UNSIGNED NOT NULL,
    summary TEXT NULL,
    author_id INT UNSIGNED NOT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_books_author_id (author_id),
    CONSTRAINT fk_books_author_id FOREIGN KEY (author_id) REFERENCES authors (id)
        ON UPDATE CASCADE ON DELETE RESTRICT
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;

-- Sample data, with fixed ids so that book 3 is Kindred everywhere
INSERT IGNORE INTO authors (id, name, bio) VALUES
    (1, 'Ursula K. Le Guin', 'American author of science fiction and fantasy, known for the Earthsea books.'),
    (2, 'Octavia E. Butler', 'American science fiction author, the first to receive a MacArthur fellowship.'),
    (3, 'Italo Calvino', 'Italian writer of playful, inventive novels and short stories.');

INSERT IGNORE INTO books (id, title, published_year, summary, author_id) VALUES
    (1, 'A Wizard of Earthsea', 1968, 'A gifted boy learns magic and must face the shadow he set loose.', 1),
    (2, 'The Left Hand of Darkness', 1969, 'An envoy visits a planet whose people have no fixed sex.', 1),
    (3, 'Kindred', 1979, 'A young woman is pulled back in time to a plantation in Maryland.', 2),
    (4, 'Parable of the Sower', 1993, 'In a collapsing California, a teenager starts a new belief system.', 2),
    (5, 'Invisible Cities', 1972, 'Marco Polo describes imaginary cities to the emperor Kublai Khan.', 3);
```
Then give `books` its `isbn` column with a [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations) (a table that holds rows is never changed in `create_db.sql`). Run `docker compose exec dev-box php caligrafer.php migrate make add_books_isbn`; it prints ` application/migrations/<number>_add_books_isbn.sql written: add its SQL, then php caligrafer.php migrate`. Make that file read:
```sql
-- add_books_isbn
-- Runs once (php caligrafer.php migrate, and at every deploy). Never edit it after it ran: write a new one.
-- One statement: the column and its unique index are added together, or not at all.

ALTER TABLE books
    ADD COLUMN isbn VARCHAR(20) NULL AFTER summary,
    ADD UNIQUE KEY uq_books_isbn (isbn);
```
Run:
```bash
docker compose exec dev-box php caligrafer.php sql application/models/Bookshelf/create_db.sql
docker compose exec dev-box php caligrafer.php migrate
```
Expected: ` application/models/Bookshelf/create_db.sql run on caligrafy`, then ` OK   <number>_add_books_isbn.sql` and ` 1 migration(s) run on caligrafy`.

**2. The models.** Write `application/models/Bookshelf/Author.php`:
```php
<?php

use Caligrafy\Model;

// One Author = one row of the authors table (Author::query() reads authors: the class name in lower case, plus s)
class Author extends Model {

    // one public property per column of the table
    public $id;
    public $name;
    public $bio;
    public $created_at;
    public $modified_at;
}
```
Write `application/models/Bookshelf/Book.php`:
```php
<?php

use Caligrafy\Model;

// One Book = one row of the books table. Book::with('author') adds the row of authors whose id is author_id
class Book extends Model {

    // one public property per column of the table
    public $id;
    public $title;
    public $published_year;
    public $summary;
    public $isbn;
    public $author_id;
    public $created_at;
    public $modified_at;
}
```
The models need no relationship methods: `Book::with('author')` reads the author from `author_id` ([Relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships)).

**3. The capabilities.** The pages never read the tables themselves: capabilities do, and the same ones serve REST, the JS client and AI agents. Create each file with `docker compose exec dev-box php caligrafer.php service Bookshelf/<Name> --scope books:read --read-only` (`--scope books:write` without `--read-only` for `CreateBook`), then make it read as below. `application/services/Bookshelf/ListBooks.php`:
```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;

// list_books: the catalog, sorted by title, 20 books per page, each with its author. Anyone may read it
#[Capability(
    name: 'list_books',
    description: 'Lists the books of the Bookshelf catalog, sorted by title, 20 per page, each with its author (id, name, bio). Give author_id to list only the books of one author, and page for the next pages. Returns data (the books), total, page, per_page and pages.',
    scope: 'books:read',
    readOnly: true,
    public: true
)]
class ListBooks extends Service
{
    public $rules = array('author_id' => 'integer', 'page' => 'integer');
    public $descriptions = array(
        'author_id' => 'Optional: only the books of this author',
        'page' => 'Optional: the page, 1 by default (20 books per page)'
    );

    public function handle(array $input, Context $context)
    {
        // two queries for the page (the count, then the books) and one for all their authors
        $query = Book::with('author')->orderBy('title');
        if (!empty($input['author_id'])) {
            $query->where('author_id', $input['author_id']);   // the value is bound, never pasted into the SQL
        }
        return $query->paginate(20, $input['page'] ?? 1);
    }
}
```
`application/services/Bookshelf/GetBook.php`:
```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;
use Caligrafy\ServiceError;

// get_book: one book with its author, or "not found"
#[Capability(
    name: 'get_book',
    description: 'Returns one book of the catalog with its author (id, name, bio), by the id of the book.',
    scope: 'books:read',
    readOnly: true,
    public: true
)]
class GetBook extends Service
{
    public $rules = array('id' => 'required|integer');
    public $descriptions = array('id' => 'The id of the book');

    public function handle(array $input, Context $context)
    {
        $book = Book::with('author')->find($input['id']);
        if (!$book) {
            throw ServiceError::notFound("There is no book #{$input['id']}");
        }
        return $book;
    }
}
```
`application/services/Bookshelf/CreateBook.php`:
```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;

// create_book: adds a book, with the same rules whoever calls it
#[Capability(
    name: 'create_book',
    description: 'Adds a book to the Bookshelf catalog and returns it with its id and its author. The author must already exist: use list_authors to find author_id. The ISBN is optional and unique.',
    scope: 'books:write',
    public: true   // for now: lesson 11 closes it
)]
class CreateBook extends Service
{
    public $rules = array(
        'title' => 'required|max_len,200',
        'published_year' => 'required|integer|min_numeric,1450|max_numeric,current_year',
        'summary' => 'max_len,2000',
        'isbn' => 'alpha_numeric_dash|max_len,20|unique,books.isbn',
        'author_id' => 'required|integer|exists,authors.id'
    );
    public $filters = array('title' => 'trim', 'summary' => 'trim', 'isbn' => 'trim');
    public $descriptions = array(
        'title' => 'The title of the book',
        'published_year' => 'The year it was first published, for example 1969 (not after this year)',
        'summary' => 'Optional: one or two sentences about the book',
        'isbn' => 'Optional: its ISBN, digits and dashes, for example 978-0-441-47812-5; two books never share one',
        'author_id' => 'The id of its author (list_authors)'
    );

    public function handle(array $input, Context $context)
    {
        // an empty ISBN is no ISBN: NULL, which the unique index allows on many books
        $input['isbn'] = ($input['isbn'] ?? '') === '' ? null : $input['isbn'];
        $id = Book::insert($input);   // one INSERT, every value bound; returns the id of the new book
        return Book::with('author')->find($id);
    }
}
```
`application/services/Bookshelf/ListAuthors.php`:
```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;

// list_authors: every author, sorted by name. Anyone may read it
#[Capability(
    name: 'list_authors',
    description: 'Lists the authors of the Bookshelf catalog, sorted by name: id, name and bio.',
    scope: 'books:read',
    readOnly: true,
    public: true
)]
class ListAuthors extends Service
{
    public function handle(array $input, Context $context)
    {
        return Author::query()->orderBy('name')->get();
    }
}
```
Run `docker compose exec dev-box php caligrafer.php capabilities`: the list shows `create_book`, `get_book`, `list_authors` and `list_books`. (`public: true` opens them to every visitor while you try them; [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability#secure) shows how to close them.)

**4. The routes.** In `application/config/routing/web.php`, above `Route::run();`, write:
```php
    // BOOKSHELF PAGES: rendered on the server with the data of the capabilities; the form calls one capability
    Route::page('/books', 'Bookshelf/books', ['data' => ['books' => 'list_books', 'authors' => 'list_authors'], 'query' => ['author_id']]);
    Route::form('/books', 'create_book', ['success' => '/books/{id}', 'flash' => 'Book added']);
    Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book'], 'notFound' => 'Bookshelf/notfound']);
    Route::download('/authors.csv', 'list_authors', ['filename' => 'authors.csv']);   // the same capability, as a file
```
+ `/books` gives its view `$books`, the page of books of `list_books` (`?page=2` and `?author_id=2` reach it as its inputs), `$authors`, the answer of `list_authors`, and `$author_id`, the `?author_id=` of the address (`''` when absent), which the links to the next pages keep.
+ `/books/3` calls `get_book` with `id = 3` and gives the view `$book`, with its `author`; a missing book renders `Bookshelf/notfound` with status `404`.
+ A `POST /books` calls `create_book` with the form's fields, then goes to the new book's page (`{id}` is the id of the book it returns).
+ `/authors.csv` is the list of authors as a spreadsheet ([Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#download)).

**5. The catalog page.** Write `application/views/Bookshelf/books.pug`:
```pug
extends ../default/master/site

//- The catalog: Route::page gives it $books (list_books: a page of books) and $authors (list_authors).
//- The form posts to Route::form('/books', 'create_book'): a refusal comes back here with errors(), old() and flash('error')

block title
    | Bookshelf

block content
    section.cq-hero.cq-hero--page
        h1.cq-display Bookshelf
        p.cq-lead The books we love. The same catalog that the REST API and AI agents use.

    section.cq-band.cq-band--tight
        .cq-inner.cq-inner--narrow
            if flash('success')
                p.cq-alert(role='status')= flash('success')

            form(method='POST', action="{$home}books", novalidate)
                =csrf()
                .cq-form-grid.cq-form-grid--2
                    .cq-field
                        label(for='title') * Title
                        input#title.form-control(type='text', name='title', value=old('title'), maxlength='200')
                        if errors('title')
                            p.cq-field-error= errors('title')
                    .cq-field
                        label(for='author_id') * Author
                        select#author_id.form-select(name='author_id')
                            each $a in $authors
                                option(value=$a['id'], selected=$a['id'] == old('author_id'))= $a['name']
                        if errors('author_id')
                            p.cq-field-error= errors('author_id')
                    .cq-field
                        label(for='published_year') * Year
                        input#published_year.form-control(type='number', name='published_year', value=old('published_year'), placeholder='1969')
                        if errors('published_year')
                            p.cq-field-error= errors('published_year')
                    .cq-field
                        label(for='isbn') ISBN
                        input#isbn.form-control(type='text', name='isbn', value=old('isbn'), placeholder='Optional', maxlength='20')
                        if errors('isbn')
                            p.cq-field-error= errors('isbn')
                .cq-field
                    label(for='summary') Summary
                    input#summary.form-control(type='text', name='summary', value=old('summary'), placeholder='Optional', maxlength='2000')
                button.btn.btn-primary(type='submit') Add book
            if flash('error')
                p.cq-field-error(role='alert')= flash('error')

    section.cq-band.cq-band--tight
        .cq-inner.cq-inner--narrow
            h2.cq-heading Books
            if $books['total'] == 0
                p.cq-empty-state No books here yet: add the first one above.
            else
                ul.cq-rows
                    each $b in $books['data']
                        li.cq-row
                            .cq-row-main
                                p.cq-row-title
                                    a(href="{$home}books/{$b['id']}")= $b['title']
                                p.cq-row-meta
                                    a(href="{$home}books?author_id={$b['author_id']}")= $b['author']['name']
                                    | , #{$b['published_year']}
                //- the next and previous pages keep the author of the address (?author_id=2)
                - $filter = $author_id !== '' ? '&author_id=' . (int) $author_id : '';
                p.cq-auth-note
                    | Page #{$books['page']} of #{$books['pages']}, #{$books['total']} books
                    if $books['page'] > 1
                        |  · 
                        a(href="{$home}books?page=" . ($books['page'] - 1) . $filter) Previous
                    if $books['page'] < $books['pages']
                        |  · 
                        a(href="{$home}books?page=" . ($books['page'] + 1) . $filter) Next
            p.cq-auth-note
                a(href="{$home}books") All books
                |  · 
                a(href="{$home}authors.csv") The authors as a spreadsheet (CSV)
```
`$home` is the address of the application (set by the master, ending with `/`), `csrf()` writes the hidden `_token` field every form needs, and a capability's answer reaches the view as plain arrays (`$b['author']['name']`). `#{...}` prints a PHP value inside text.

**6. The page of one book.** Write `application/views/Bookshelf/book.pug`:
```pug
extends ../default/master/site

//- One book: Route::page gives it $book (get_book: the book with its author).
//- Declarative routes adds its edit and delete forms (update_book, delete_book)

block title
    = $book['title'] . ' · Bookshelf'

block content
    section.cq-hero.cq-hero--page
        h1.cq-display= $book['title']
        p.cq-lead
            | by #{$book['author']['name']}, #{$book['published_year']}

    section.cq-band.cq-band--tight
        .cq-inner.cq-inner--narrow
            if flash('success')
                p.cq-alert(role='status')= flash('success')
            p= $book['summary'] ?: 'No summary yet.'
            if $book['isbn']
                p.cq-row-meta ISBN #{$book['isbn']}
            p.cq-auth-note
                a(href="{$home}books") All books
```
Write `application/views/Bookshelf/notfound.pug`:
```pug
extends ../default/master/site

//- The notFound view of Route::page: $message is the message of the capability that refused (get_book)

block title
    | Not found · Bookshelf

block content
    section.cq-hero
        h1.cq-display Not found
        p.cq-lead= $message
        .cq-cta
            a.btn.btn-primary(href="{$home}books") All books
```

**7. Try it.** Open `http://localhost:8080/books`:
+ Each row shows a title, its author and its year, sorted by title, and `Page 1 of 1, 5 books` under them.
+ Type `Dawn`, choose Octavia E. Butler, leave the year empty, press **Add book**: the page comes back with `The Published Year field is required` under the year, `Some of the inputs are invalid` under the form, `Dawn` still in the title and Octavia E. Butler still chosen.
+ Type `1987` as the year and press **Add book**: you land on `/books/6`, which shows `Book added` and `by Octavia E. Butler, 1987`. Reload it: the message is gone (it lasts one request).
+ Click *Octavia E. Butler* under a book: `/books?author_id=2` lists her three books.
+ Open `http://localhost:8080/books/999`: *Not found*, `There is no book #999`, status `404`.

**Check**
+ `/books` and `/books/6` look like Caligrafy's own pages (top bar, title band, rows) at desktop and phone width.
+ The form is refused without its `_token` field: `curl -X POST -d "title=x&author_id=1&published_year=2000" http://localhost:8080/books` answers `403`.
+ No controller and no SQL in a view: the routes name capabilities, and the views only print what they get.
## Reference

### <a name="structure"></a>Where the files go

| What | Where |
| --- | --- |
| Views (`.pug`), in any sub-folders | `application/views/`, for example `application/views/Bookshelf/books.pug` |
| Caligrafy's masters and modules | `application/views/default/master/` (`site.pug`, `layoutblocks.pug`), `application/views/default/modules/` |
| Stylesheets, scripts, images, fonts | `public/` (`public/css/`, `public/js/`, `public/images/`): `application/` is never served to browsers |

A view is named by its path from `application/views/`, without `.pug`: `'Bookshelf/books'`.

### <a name="simpleview"></a>A page without data

```php
Route::page('/about', 'about');
Route::page('/about', 'about', ['with' => ['sentence' => 'Built with Caligrafy']]);   // fixed values: $sentence
```

### <a name="parameterview"></a>A page with data: `Route::page`

`Route::page($route, $view, $options)` renders the view through the framework's page controller (`framework/core/PageController.php`):

| Option | Default | What it does |
| --- | --- | --- |
| `data` | none | `['books' => 'list_books']`: calls each capability and gives its answer to the view under that name. The capability must exist and be `readOnly`, otherwise every visit answers `500` (`LogicException`). Its inputs are the query string and the route variables, the route variables winning (`/books/3?id=9` gives `id = 3`); only the inputs in its `$rules` reach it. Fixed inputs: `['book' => ['get_book', ['id' => 3]]]` |
| `with` | none | fixed values for the view: `['with' => ['install' => true]]` |
| `signedIn` | `false` | `true` sends visitors to `/login` (needs `Auth::authentication(...)` in `web.php`) |
| `level` | `0` | sends people whose `permissions` are below it to `/notAuthorized` |
| `notFound` | none | a view shown with status `404` when a capability answers `not_found`, `invalid` or `conflict`; it gets the route variables, `with`, `$message`, `$authorized` and `$user` |
| `comeBack` | `false` | `true`, with `signedIn` or `level`: visitors go to `/login?return=<this page>` and come back after signing in |
| `visitorsOnly` | none | a path: people already signed in are sent there (a sign-up page) |
| `query` | none | what the view gets of the query string: `['show']` gives `$show` (a string, `''` when absent), `['sort' => 'title']` a default |

Every view rendered by `Route::page` gets:

| Variable | Value |
| --- | --- |
| the route variables | `$id` for `/books/{id}` |
| the `with` values and the `data` answers | `$books`, `$book`... (plain arrays) |
| `$authorized` | `true` when someone is signed in |
| the names of the `query` option | `$sort`, `$show`... as strings |
| `$user` | `['id', 'username', 'permissions']` of who is signed in, or `null` |

The view gets the query string only through `query`; the `data` capabilities get all of it as inputs. The names `authorized` and `user` are reserved (`LogicException`). When a capability refuses: a visitor (`unauthenticated`) is sent to `/login` when authentication is on; `forbidden` answers `[ERROR 1006]` (403); `not_found`, `invalid` and `conflict` answer `[ERROR 1005]` (404), or the `notFound` view.

### <a name="formhelpers"></a>Forms: `errors()`, `old()` and `flash()`

A form that posts to [`Route::form`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form) comes back to the page with what the page needs to show:

| Helper | Returns |
| --- | --- |
| `errors('title')` | the message of one field, or `null` |
| `errors()` | every field's message, as an array |
| `old('title', $default = '')` | what the field held when the form was refused; never a field whose name matches `pass`, `secret`, `token`, `card`, `cvc`, `cvv` or `iban`, and never a file |
| `flash('success')` | the `flash` message of the `Route::form` that succeeded |
| `flash('error')` | the message of a refused form (`Some of the inputs are invalid` by default, or the route's `error` option) |
| `flash('saved', 'Your changes are saved')` | keeps a message for the next request |
| `csrf()` | the hidden `_token` field: write `= csrf()` in every form |
| `methodField('PUT')` | the hidden `_method` field, for a `Route::form` with `'method' => 'PUT'` or `'DELETE'` |

They last **one request**: the first page after the post reads them, then they are gone. Point `success` and `back` of `Route::form` at the page that shows them.

### <a name="templates"></a>Masters, blocks and Pug in Caligrafy

New pages extend the master **`default/master/site`** (`application/views/default/master/site.pug`): a light top bar with the Caligrafy mark, the page, a footer. Its blocks:

| Block | What goes in it |
| --- | --- |
| `title` | the text of the browser tab (default `Caligrafy`) |
| `brand` | the name after the mark in the top bar |
| `nav_links` | the links on the right of the top bar; on phones a **Menu** button opens them. By default *Sign in* / *Create account*, or *Sign out* when someone is signed in |
| `content` | the page |
| `footer` | the footer (default: the copyright of `copyright()`) |
| `additional_css` | more `link` tags, loaded after Caligrafy's stylesheets and before a design style |
| `additional_scripts` | more scripts, at the end of the page |

**The top bar stays put from page to page** (2.21.4). `layout.css` sets `html { scrollbar-gutter: stable }`, so a short page and a long one keep the same room for the scrollbar. To mark the current link in `nav_links`, change its color or underline it: never a heavier `font-weight`, because Inter is loaded at 400 and 500 only, and a heavier weight is faked by the browser and makes the text change width.

The master also links the web app manifest, the icons and the page's [social card](https://github.com/caligrafy/caligrafy-quill/wiki/9.3-Metadata-&-Social-Rich-Cards), sets `$home` (the application's address, ending with `/`), and links its stylesheets with their modification time (`?v=...`) so browsers fetch every change. Link your own files the same way: `script(src=$home . 'public/js/books.js?v=' . @filemtime(PUBLIC_PATH . 'js/books.js'))`.

<a name="introduction"></a>**Pug in Caligrafy.** Pug writes HTML by indentation: `p.cq-lead Hello` is `<p class="cq-lead">Hello</p>`. Caligrafy runs Pug with **PHP expressions** ([Phug](https://phug-lang.com)):

| Write | Not |
| --- | --- |
| `'by ' . $author['name']` (PHP joins strings with `.`) | `'by ' + $author['name']` (an error: "Unsupported operand types") |
| `p= $book['title']` (escaped), `p!= $html` (not escaped: only for HTML you made) | `p= $book.title` |
| `if $book` / `each $book in $books['data']` with the lines under it | `- if ($book) echo 'x'` on one line (does not compile) |
| `p From &#36;40 a month` | `p From $40 a month` (`$40` is read as a variable and vanishes) |
| `- $position = sprintf('%d of %d', $i + 1, count($books))` then `figure(aria-label=$position)` | an attribute value with parentheses and `.` (`aria-label=($i + 1) . ' of ' . count($books)`): a parse error |
| `- $open = isset($signUp) ? $signUp : \Caligrafy\AuthRoutes::signUpOpen()` then `if $open` | a `::` on the `if` line after `??` or in a ternary (`if isset($signUp) ? $signUp : \Caligrafy\AuthRoutes::signUpOpen()`): it is read as a Pug filter, `Failed to compile: Unknown filter signUpOpen` |

`php caligrafer.php doctor` points to the `$` before digits and the one-line `- if` it finds in `application/views`.

### <a name="debug"></a>Compiled views, debug mode and the Optimizer

Phug turns each `.pug` view into PHP. Caligrafy keeps that PHP between requests (`framework/core/View.php`):

| Setting in `.env` | Effect |
| --- | --- |
| (default) | a view is compiled once, then again only when it, or a file it `extends` or `include`s, is saved with a newer modification time. Edit a view, reload the page: you see the change |
| `APP_DEBUG=true` | Phug's debug mode: an error names the `.pug` file and its line, in a page with the source. It makes every page about three times slower. Views compiled this way are kept in their own folder |
| `APP_DEBUG=false` (production) | no debug mode: an error in a view answers `[ERROR 500] Internal Server Error`. An up-to-date compiled view runs through Phug's Optimizer, which includes the compiled PHP without loading Phug's compiler |
| `VIEW_OPTIMIZER=false` | no Optimizer: every view goes through Phug's renderer (still cached) |
| `VIEW_CACHE=false` | no cache: every view is compiled on every request |

The compiled views live in the system's temporary folder, one folder per project and per system user, readable by that user only: `caligrafy-views-<project>-<user>` and, in debug mode, `caligrafy-views-debug-<project>-<user>`. A project that sets Phug's `cache_dir` itself keeps its folder. A new container starts with empty folders.

**When to clear them.** Copying files with tools that keep the old modification times (`rsync -a`, `cp -p`, an unzipped archive) can leave a compiled view newer than the file you copied, so the old page keeps showing. Run, as the system user of the web server (each user has its own folders):
```bash
docker compose exec dev-box php caligrafer.php cache clear
```
Expected: `Cache (<store>) emptied; <n> compiled view and class map file(s) removed`. It empties both view folders, the class map and the [cache](https://github.com/caligrafy/caligrafy-quill/wiki/Caching). Restarting the container does the same for a Docker server. Deploys from the production image and Caligrafy Cloud are not concerned.

### <a name="install"></a>Mobile: install to home screen

Browsers can install a Caligrafy application on a phone, a tablet or a computer: it opens from its own icon, full screen, without the browser bar. Installation needs HTTPS (or `localhost`).

+ **The manifest.** Both masters link `public/manifest.webmanifest`: the name, the white colors and the icons of the app (`public/images/resources/icon-192x192.png` and `icon-512x512.png`, plus the Apple touch icons). Its `start_url` and `scope` are `../`, relative to the manifest: they point to the root of the application, whatever `APP_ROOT` is. Change `name`, `short_name` and the icons to brand your app; keep a 192x192 and a 512x512 PNG (Chrome needs both). New apps start with Caligrafy's black logo in `favicon.ico`, the Apple touch icons and these two: replace the files with your own, keeping their names (the pages link them with their modification time, so browsers fetch them again).
+ **The install button.** Give the page `install`: `Route::page('/', 'default/index', ['with' => ['install' => true]]);`. The master then includes `default/modules/install.pug`: on Chrome, Edge and Android an **Install** button (`btn-primary`) appears when the browser offers it, and **Not now** (`btn-secondary`) hides it; on iPhone and iPad Safari a short hint says to tap Share, then Add to Home Screen, and **Got it** hides it. Nothing shows once the app is installed or after the visitor dismissed it (`localStorage` key `caligrafy-install-dismissed`). The box is styled inside the module (`.caligrafy-install`): restyle it in your own CSS.
+ **The offline page.** `PWA_SERVICE_WORKER=true` in `.env` registers `public/sw.js` (off by default). It does one thing: when a page cannot load because the device is offline, it shows `public/offline.html`. It never caches pages, API routes, `POST` requests or signed-in pages. Edit `offline.html` (self-contained: no external files) and change `CACHE` in `sw.js` when you do. Setting it back to `false` unregisters it on the next visit. The root `.htaccess` sends `Service-Worker-Allowed` for `public/sw.js` and the `application/manifest+json` type for `.webmanifest` files. `php caligrafer.php doctor` checks the manifest and its icons, and, with the service worker on, its files and HTTPS in production.
+ **Client apps** of `public/<app>` link the manifest themselves in their `<head>`: `<link rel="manifest" href="<?php echo session('public').'manifest.webmanifest'; ?>">` and `<meta name="theme-color" content="#ffffff">` install the whole application. To install one app on its own, copy `public/manifest.webmanifest` to `public/<app>/manifest.webmanifest`, set `"start_url": "./"`, `"scope": "./"`, `"id": "./"` and its `name`, prefix the icons with `../` (`"../images/resources/icon-192x192.png"`) and link that copy. A Vite single page app puts the copy and its icons in its own `public/` folder and links it from `index.html` (`<link rel="manifest" href="manifest.webmanifest">`).

### <a name="designtokens"></a>One look on every device: the design tokens

`public/css/tokens.css` defines Caligrafy's look as CSS custom properties, generated from `public/css/tokens.json` (the two must match): colors (`--cq-color-ink`, `--cq-color-paper`, `--cq-color-text`, `--cq-color-text-muted`, `--cq-color-border`...), type (`--cq-font-size`, `--cq-font-line-height`), spacing (`--cq-space-1` to `--cq-space-5`, `--cq-space-gutter`), radius (`--cq-radius-control`) and breakpoints (`--cq-breakpoint-phone`, `-tablet`, `-desktop`, `-wide`). It also gives:
+ touch targets of at least `--cq-touch-target` (44px) on touch screens (`pointer: coarse`),
+ safe-area padding when the app is installed to the home screen (`display-mode: standalone`),
+ `.cq-split`: one column on phones, a list and its detail side by side from tablets up ([below](#sidebyside)).

`look.css` sets its own `--design-*` tokens (`--design-canvas`, `--design-ink`, `--design-primary`, `--design-font`...) and feeds the `--cq-*` ones from them. Use the tokens in your own styles (`color: var(--cq-color-text)`) so every experience of the application keeps one look: see [experiences](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#experiences).

### <a name="pagecomponents"></a>Caligrafy's look: the page components

Every page of Caligrafy shares one look: **a white canvas, a light top bar with the Caligrafy mark, one message per screen, full-width bands, narrow columns for forms, rows for lists, large tiles for links, black for the main action, Inter type, no cards and no shadows**, at every size. Three stylesheets give it; the master `site.pug`, the Vue app template and the single page app template link them:

| Stylesheet | What it holds |
| --- | --- |
| `public/css/layout.css` | the structure: top bar, title bands, bands, forms, rows, tiles, account area, footer |
| `public/css/look.css` | the look: its `--design-*` tokens, Inter, black buttons, fields, the mark |
| `public/css/camera.css` | full-screen camera pages: face detection, machine learning, face sign-in |

A page is a title band, then bands. The parts:

| Part | Classes |
| --- | --- |
| Full-screen message | `section.cq-hero > h1.cq-display + p.cq-lead + .cq-cta > .btn` (a landing, a welcome) |
| Title band | `section.cq-hero.cq-hero--page`, same children: the title of an ordinary page |
| Band | `section.cq-band > .cq-inner > h2.cq-heading + p.cq-lead + ...`; `.cq-band--surface` (ash), `.cq-band--tight`, `.cq-inner--narrow` (720px), `.cq-center` |
| Sign-in style form | `main.cq-auth > h1 + form > .cq-field (label + .form-control) + .btn`; `.cq-auth--wide`, `.cq-or`, `p.cq-auth-note` |
| Form on a page | `.cq-form-grid(.cq-form-grid--2) > .cq-field`: fields side by side from tablets up; `.cq-btn-block`, `label.cq-hidden-label` |
| Messages | `.cq-alert` (`.cq-alert--error`) above a form (`include ../default/modules/notice` shows `$error` and `$message`), `p.cq-field-error` under a field, `p.cq-empty-state` for an empty list |
| Choices | `.cq-segments > button` (`.active`) with `span.cq-count` |
| List | `ul.cq-rows > li.cq-row` (`.is-done` greys it) with `.cq-row-check`, `.cq-row-main` (`.cq-row-title`, `.cq-row-meta`), `.cq-row-actions` |
| Links | `.cq-tiles > a.cq-tile > h3 + p + span.cq-tile-link`: one, two or three columns by width |
| Side by side | `.cq-split > section.cq-split-main + aside.cq-split-detail` ([below](#sidebyside)) |
| Figures | `.cq-stats > .cq-stat > .cq-stat-value + .cq-stat-label`, `span.cq-badge` |
| Account area | `.cq-account > nav.cq-account-nav > a(href='#section')` + `.cq-account-main > section(id)`: a side menu on desktops that marks the section on screen |
| Text and code | `.cq-doc` (long text), `.cq-code`, `pre.cq-pre` |

The same classes work in Vue apps and single page apps. Keep to black and white (`btn-primary` is black, `btn-secondary` ash): no Bootstrap color classes. The top bar has its own button (Menu): scripts find their elements by id, never with `document.querySelector('button')`. In `site.pug`, `body` is a flex column (the footer waits one screen down): put content in a block (`section.cq-band`), never a bare `a` or `span` directly in `body`, and keep a page's own footer a `footer.cq-footer` directly in `body`.

### <a name="sidebyside"></a>A list and its detail, side by side

A page that shows a list and the item opened (a finder, a catalog and its add form) puts them side by side right after its title band: the list on the left, the item in an ash panel on the right that stays in view while the list scrolls. On phones the panel comes after the list. A form in the panel takes one field a line.

```pug
section.cq-hero.cq-hero--page
  h1.cq-display Find a book
  p.cq-lead Type a few words: the books answer as you type.

.cq-split
  section.cq-split-main
    .cq-field
      label(for='query') Search
      input#query.form-control(type='search')
    ul#books.cq-rows
  aside#book.cq-split-detail(aria-live='polite')
    p.cq-empty-state Open a book to read about it.
```
The course's [finder and single page application](https://github.com/caligrafy/caligrafy-quill-course/wiki) are built this way.

**Camera pages.** Face detection, machine learning and face sign-in fill the screen with the camera (`camera.css`, `.cq-camera`): the title and the status float at the top, the actions at the bottom, an oval guides the face, a sheet holds a form over the camera. See [Face Detection](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition) and [Machine Learning](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.3-Machine-Learning).

### <a name="designstyles"></a>Another look: design styles

Caligrafy's look is the default. To give the whole application another one, pick a [design style](https://github.com/caligrafy/caligrafy-quill/wiki/Design-Styles) (`php caligrafer.php design use <name>`, `DESIGN_STYLE` in `.env`) and write its stylesheet (`/caligrafy-quill:design` in Claude Code). The masters load `public/css/designs/<name>.css` last, so the same markup takes the new look and your views do not change. An empty `DESIGN_STYLE` is the Caligrafy look again.
## Other ways and under the hood

These still work. `Route::page` with `data` replaces them for pages, and `Route::form` for forms. A page that depends on more than one capability's answer (a redirect or a view, say) is a web-only capability that returns `Web::view()`: [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#action).

+ **`view()` from a controller.** `return view('Bookshelf/books', ['books' => $this->call('list_books'), 'authors' => $this->call('list_authors')]);` in a controller extending `Caligrafy\Controller` (`$this->view()` is the same). In a controller you keep, it must pass `$authorized` itself, or the top bar's signed-in parts follow only the session.
+ **A closure that returns a view.** `Route::get('/hello', function () { return view('hello'); });` gets only what the closure passes: no `$authorized`, no `$user`.
+ **`view()` answers JSON too.** `view($name, $data)` prints `$data` as JSON and ends the request when the request sends `Accept: application/json` (and not `text/html`), or when `$name` is `null`; `api($data)` is `view(null, $data)`. Set the status first: `http_response_code(422); return api([...]);`. Nothing runs after `view()` or `api()`.
+ **Hand-written forms** posted to a controller: `= csrf()` in the form, `= methodField('PUT')` for `PUT` and `DELETE`, and the controller validates with `$this->check()`. See [Helpers, Forms and REST API](https://github.com/caligrafy/caligrafy-quill/wiki/9.-Helpers-,-Forms-&-REST-API#forms).

### <a name="default-layout-and-bootstrap-5"></a>The older master: `layoutblocks` and Bootstrap 5

Pages written before 2.11.0 extend `default/master/layoutblocks`. It keeps working and takes the new look from `look.css`. It loads Bootstrap 5.3 (`scripts('bootstrap_css')`, `scripts('bootstrap_script')`, no jQuery) and `public/css/theme.css`, which keeps the Caligrafy black and white on top of Bootstrap: black `btn-primary`, white `btn-secondary`, black focus rings, buttons in forms at most 150px wide. Its header is fixed (60px): content starts under it. Its body carries `class='caligrafy-layout'`, which scopes the Bootstrap 3 heading margins `theme.css` keeps; `theme.css` must load after Bootstrap. Bootstrap 5 breakpoints are one step lower than Bootstrap 3's: a Bootstrap 3 `col-sm-*` is a Bootstrap 5 `col-md-*`, `col-md-*` is `col-lg-*`, `hidden-xs` is `d-none d-md-block`. Its card components (`main.cq-page > .cq-card`, `form.cq-form > .cq-fields`, `ul.cq-list > li.cq-item`, `.cq-tabs`, `p.cq-error`, `p.cq-empty`) live in `tokens.css`. A project made before 2.11.0 gets `site.pug` with `php caligrafer.php upgrade --apply` and the stylesheets with `php caligrafer.php update`: see [Upgrading](https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading#upgrading).
## Common mistakes

+ **`+` to join strings in a view**: the page becomes a template error. Use `.`.
+ **A `data` capability that writes**: `Route::page` accepts only `readOnly` capabilities; every visit answers `500`.
+ **Reading `$_GET` in a view**: the view gets the query string only through the `query` option of `Route::page`; a capability gets it through its `$rules`.
+ **A `success` page that redirects again**: the flash messages and errors are read by the first page after the post, then gone.
+ **A `form` without `method='POST'`**: when its script does not run, the browser sends the fields in the address. Give every form `method='POST'`.
+ **A changed view that does not show after a copy**: `php caligrafer.php cache clear` as the web server's user.
+ **`document.querySelector('button')`** finds the top bar's Menu button: use ids.
## Related pages

+ [Declarative routes: `Route::form`, `Route::auth`, `Route::download`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes)
+ [Routing: page routes](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing)
+ [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability)
+ [Queries: the query builder](https://github.com/caligrafy/caligrafy-quill/wiki/Queries)
+ [Design styles](https://github.com/caligrafy/caligrafy-quill/wiki/Design-Styles)
+ [Vue apps: the flow of information](https://github.com/caligrafy/caligrafy-quill/wiki/9.7-Understanding-the-flow-of-information)
>[Next Section: Learn about Controllers](https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Design-Styles -->

A **design style** gives the whole application another look, taken from the description of a design system, without changing your views. One setting in `.env` picks it (`DESIGN_STYLE`), one stylesheet applies it (`public/css/designs/<name>.css`), and emptying the setting brings back [Caligrafy's own look](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#pagecomponents): a white canvas, a light top bar with the Caligrafy mark, black for the main action, Inter type, no cards. Since 2.8.0.
## <a name="restyle"></a>With Claude

A style is a text file written for AI agents, so Claude writes its stylesheet. In Claude Code, with the [Caligrafy plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin):

```text
/caligrafy-quill:design linear.app
```

Claude reads the whole `DESIGN.md` of the style (its tokens and its prose), looks at the pages and client apps of your project, and writes **one** file, `public/css/designs/linear.app.css`: the style's colors, fonts (free substitutes from Google Fonts), radii and spacing, applied first to the `--design-*` tokens of Caligrafy's look, then to the top bar and footer, the sign-in pages, the buttons and fields, every page component (`.cq-hero`, `.cq-band`, `.cq-rows`, `.cq-tiles`, `.cq-segments`...), the camera pages and the older card components. It selects the style (`design use`), then opens the sign-in pages and your pages at desktop and phone width and fixes what does not read well. It never edits `look.css`, `layout.css`, `tokens.css`, `theme.css`, `styles.css` or your views. Without a name it asks which style; your own brand becomes `application/design/<name>/DESIGN.md` first. `/caligrafy-quill:design off` goes back to the Caligrafy look.

**Check** before you say OK:
+ `php caligrafer.php design status` says `OK  <name>: public/css/designs/<name>.css loaded after the Caligrafy stylesheets`.
+ The sign-in page, a list page and a form page read well at desktop and phone width: text in fields and on buttons, error messages, the top bar and its Menu.
+ `git status` shows one new file, `public/css/designs/<name>.css` (and `.env`): nothing else changed.
+ A Vite single page app imports the stylesheet in its `src/main.js` and was rebuilt.
## <a name="pick"></a>By hand

You pick a style, write its stylesheet, check it, and go back to the Caligrafy look. Commands run in the project folder with the Docker server of the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart); with PHP on your computer, drop `docker compose exec dev-box` (`.bin/caligrafer design ...` works too).

**1. See the styles.** Run:
```bash
docker compose exec dev-box php caligrafer.php design list
```
The first line is `85 styles (* selected, + stylesheet written). DESIGN_STYLE empty = Caligrafy's own look (now)`, then one line per style: its name, where it comes from, one line of description.

**2. Read one.** Run `docker compose exec dev-box php caligrafer.php design show linear.app`: its whole `DESIGN.md`. Note its colors (`canvas`, `surface-1`, `ink`, `ink-muted`, `ink-subtle`, `hairline`, `primary`, `primary-hover`, `on-primary`) and its radii (`rounded`).

**3. Select it.** Run:
```bash
docker compose exec dev-box php caligrafer.php design use linear.app
```
Expected:
```text
 DESIGN_STYLE=linear.app in .env. Its stylesheet public/css/designs/linear.app.css is not written yet: pages keep Caligrafy's own look until it is.
```
Nothing changes on the pages yet: a style without its stylesheet keeps the Caligrafy look.

**4. Write the stylesheet.** Write `public/css/designs/linear.app.css`, with the values of the `DESIGN.md`:
```css
/* linear.app: from framework/design/vendor/awesome-design-md/linear.app/DESIGN.md */
:root {
  --design-canvas: #010102;
  --design-surface: #0f1011;
  --design-ink: #f7f8f8;
  --design-body: #d0d6e0;
  --design-muted: #8a8f98;
  --design-hairline: #23252a;
  --design-primary: #5e6ad2;
  --design-primary-hover: #828fff;
  --design-on-primary: #ffffff;
  --design-radius-control: 6px;
  --design-radius-card: 8px;
}

/* a dark canvas: the fields and the top bar too */
html body .form-control,
html body .form-select {
  background-color: var(--design-surface);
  border-color: var(--design-hairline);
  color: var(--design-ink);
}
html body .cq-nav {
  background-color: rgba(1, 1, 2, 0.85);
  border-bottom-color: var(--design-hairline);
}
```
The `--design-*` tokens go on `:root`: `look.css` builds the `--cq-*` tokens of every page from them there. Every other rule starts with `html body`: Caligrafy's stylesheets set fonts on `body *` and buttons on `html .btn-primary`, and a design stylesheet wins by being more specific, not with `!important`.

**5. Check it.** Run `docker compose exec dev-box php caligrafer.php design status`. Expected:
```text
 OK  linear.app: public/css/designs/linear.app.css loaded after the Caligrafy stylesheets
```
Open `http://localhost:8080/books` (or any page): a near-black page, light headings and text, dark fields, a lavender **Add book** button. In the page source the last stylesheet of the `head` is `public/css/designs/linear.app.css?v=<number>`. `docker compose exec dev-box php caligrafer.php doctor` prints the same line (`OK    Design style: ...`).

**6. Back to the Caligrafy look.** Run:
```bash
docker compose exec dev-box php caligrafer.php design off
```
Expected: `DESIGN_STYLE= in .env: every page has Caligrafy's own look again. The stylesheets in public/css/designs/ are kept.` The pages are white again and link no design stylesheet.

**Check**
+ With the style selected, every page and every Vue app of `public/<app>` link `public/css/designs/<name>.css` last.
+ With `DESIGN_STYLE=` empty, nothing is linked and the pages look as before.
+ No file of `public/css/` other than `designs/<name>.css` was edited.
## Reference

### <a name="what"></a>What a design style is

A design style is a `DESIGN.md`: a plain-text description of a website's design system (its colors, typography, spacing, components, do's and don'ts) written for AI agents to read. Most start with YAML front matter (`colors`, `typography`, `rounded`, `spacing`, `components`); some are prose only. They live in three places:

```text
framework/design/
  vendor/<vendor>/<name>/DESIGN.md   collections copied from elsewhere, each with its license and attribution
      awesome-design-md/             84 styles from VoltAgent/awesome-design-md (MIT License, copyright VoltAgent)
  local/<name>/DESIGN.md             styles added to Caligrafy itself, their origin in local/README.md
      interstellar/                  a calm, dense laboratory operations system (cool grey canvas, Inter, one brand blue)
application/design/<name>/DESIGN.md  your own styles: put a DESIGN.md here
```

A style's name is its folder name: lowercase letters, digits, `.`, `_` and `-`. When a name exists in several places, the first wins: `application/design`, then `framework/design/local`, then each vendor in alphabetical order. `design list` shows where each style comes from; `design show <name>` also names the copies it hides.

The styles describe the visual language of public websites to inspire yours: your application keeps its own name and logo, and never presents itself as one of those sites.

### Commands

| Command | What it does |
| --- | --- |
| `php caligrafer.php design list` | every style: `*` selected, `+` stylesheet written (`--json` for a program) |
| `php caligrafer.php design show <name>` | its `DESIGN.md`, its source and its stylesheet |
| `php caligrafer.php design use <name>` | writes `DESIGN_STYLE=<name>` in `.env`, nothing else; an unknown name exits with `1` (`unknown style '<name>'`) |
| `php caligrafer.php design status` | the selected style: `OK` with its stylesheet, `WARN` for an unknown name or a stylesheet not written yet |
| `php caligrafer.php design off` | writes `DESIGN_STYLE=` and keeps the stylesheets |

You can also set it in `.env` yourself:
```bash
# DESIGN_STYLE: empty = Caligrafy's own look
DESIGN_STYLE=linear.app
```

### <a name="how"></a>How it works

+ The masters (`application/views/default/master/site.pug` and the older `layoutblocks.pug`), the Vue app template (`public/<app>/index.php`) and the camera apps link `public/css/designs/<name>.css` **last**, after `styles.css`, Bootstrap, `theme.css`, `tokens.css`, `layout.css`, `camera.css` and `look.css`, with the helper `design_stylesheet()`. In `site.pug`, a page's `additional_css` block comes before it.
+ `design_stylesheet()` returns `''` (nothing is linked) when `DESIGN_STYLE` is empty, names no style, or names a style whose stylesheet does not exist yet.
+ The link carries the stylesheet's modification time (`?v=...`), so browsers fetch every change.
+ Several stylesheets can live side by side in `public/css/designs/`: switching is `design use <other>`.
+ A client app you write yourself links it in its `public/<app>/index.php`, after its other stylesheets: `<?php if (design_stylesheet()): ?><link rel="stylesheet" href="<?php echo design_stylesheet(); ?>"><?php endif; ?>`.
+ A Vite single page app imports its CSS when it is built: add `import '../../css/designs/<name>.css'` to its `src/main.js`, after the `look.css` import, and rebuild (`npm run build`). That build then always has the style, whatever `DESIGN_STYLE` says.

### The tokens a stylesheet overrides

`look.css` sets these on `:root` and builds the `--cq-*` tokens of every page from them: `--design-canvas`, `--design-surface`, `--design-surface-raised`, `--design-ink` (headings), `--design-body` (text), `--design-muted`, `--design-placeholder`, `--design-hairline`, `--design-hairline-strong`, `--design-primary`, `--design-primary-hover`, `--design-on-primary`, `--design-focus`, `--design-error`, `--design-success`, `--design-overlay`, `--design-font`, `--design-font-code`, `--design-radius-control`, `--design-radius-card`, `--design-transition`. Override them on `:root`: set on `html body`, they would not reach the `--cq-*` tokens. Camera pages have their own `--cq-camera-*` tokens in `camera.css`. Buttons also take Bootstrap's `--bs-btn-*` variables from `theme.css`: to restyle them beyond the tokens, redefine the whole `--bs-btn-*` set on `html body .btn-primary` and set `background-color`, `border-color` and `color` too. The sign-in button is `btn btn-primary btn-secondary`: style `.btn-primary.btn-secondary` as the main action.

### <a name="online"></a>Online

Commit `public/css/designs/<name>.css` (it is part of your application) and set `DESIGN_STYLE` where the application runs: in the server's `.env`, or on Caligrafy Cloud with `php caligrafer.php cloud secret set <app> DESIGN_STYLE=<name>`. The production image leaves `framework/design/` out: only the stylesheet is needed at run time.

### <a name="update"></a>Updating the styles

`sh framework/design/vendor/awesome-design-md/sync.sh` copies the latest `DESIGN.md` files from VoltAgent/awesome-design-md (`SOURCE` in that folder records the commit); it never touches the other vendors, `local/` or `application/design/`. Another collection is another folder in `framework/design/vendor/`, with its license and a README that credits it. Framework updates bring new styles too.
## Common mistakes

+ **The style is selected but nothing changed**: its stylesheet does not exist yet. `design status` says so.
+ **The tokens on `html body`**: the canvas changes but headings keep their color, because the `--cq-*` tokens are built on `:root`. Put the `--design-*` tokens on `:root`.
+ **A dark style with white fields**: the tokens do not cover every part. Look at the fields, the top bar and the alerts, and add `html body` rules for them.
+ **Editing `look.css`, `tokens.css` or a view to restyle**: the Caligrafy look would not come back with `design off`, and the QA suite checks that `tokens.css` and `tokens.json` match. Write only `public/css/designs/<name>.css`.
+ **`!important` everywhere**: prefix the rules with `html body` instead.
+ **Online, the old look**: the stylesheet was not committed, or `DESIGN_STYLE` is not set on the server.
+ **A Vite app keeps the old look**: it needs the import in `src/main.js` and a new build.
## Related pages

+ [Views: Caligrafy's look and the page components](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#pagecomponents)
+ [Claude Code plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin)
+ [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer)
+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes -->

# Declarative routes

A **declarative route** is one line of `web.php` that connects a request to a capability: a page, a form, the sign-in
pages, the events another service posts, a file to download, an address that moved. The capability holds the rules (who
may call it, which inputs it accepts), and the route says where the person goes next.

Since 2.21.0 every request of an application can be declared, so **a new application needs no controller**: what a page
or a form cannot say (a sign-in between two sites, a page that decides where to go, a gate, a payment page) is a
web-only capability served by [`Route::action`](#action). Existing controllers keep working.

| You need | One line in `application/config/routing/web.php` |
|---|---|
| A page, with its data | `Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book']]);` |
| A page people return to after signing in | `Route::page('/books/new', 'Bookshelf/new', ['signedIn' => true, 'comeBack' => true]);` |
| A page for visitors only | `Route::page('/join', 'Bookshelf/join', ['visitorsOnly' => '/books']);` |
| A form that creates, changes or deletes | `Route::form('/books', 'create_book', ['success' => '/books/{id}']);` |
| A sign-up form that signs the person in | `Route::form('/join', 'register_user', ['signsIn' => 'id', 'success' => '/books', 'same' => [...], 'accepted' => [...]]);` |
| A form that leaves for a payment page | `Route::form('/membership/checkout', 'start_checkout', ['success' => fn ($r) => $r['url']]);` |
| Sign-in, sign-out, sign-up | `Route::auth(['home' => '/books']);` |
| Events another service posts | `Route::webhook('/stripe/events', 'record_event', ['verify' => 'stripe']);` |
| A CSV or JSON export | `Route::download('/authors.csv', 'list_authors', ['filename' => 'authors.csv']);` |
| Many files as one ZIP | `Route::download('/photos.zip', 'list_photo_files', ['as' => 'zip', 'root' => 'public/uploads/photos']);` |
| An address that moved | `Route::redirect('/old/books/{id}', '/books/{id}', 301);` |
| Anything else a browser asks | `Route::action('/authors/{author_id}/books', 'open_author_books');` |
| Every capability as a card, and an assistant | `Route::snap();` ([Snap Cards and the assistant](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant)) |
| A file in a form | the `file` rule of the capability: `'cover' => 'required\|file\|extension,png;jpg\|max_size,2mb'` |

## With Claude

```text
/caligrafy-quill:new-capability create_book books:write
"Add a 'New book' form at /books/new for signed-in people. After saving, go to the book's page and say 'Book added'.
If a field is wrong, come back to the form with the message under the field and what was typed."
```

Other requests the plugin turns into one of these lines: "let people export the books as CSV", "receive Stripe's
checkout events", "add sign-in pages", "redirect /catalog to /books", "after signing in, come back to the page you were
on", "a sign-up page with the password typed twice and a terms box", "when an author has one book, go straight to it".
What Claude writes: the capability in `application/services/<Folder>/`, the route in
`application/config/routing/web.php`, and for a form the page (`Route::page`) and its Pug view with `=csrf()`, `old()`,
`errors()` and `flash()`.

**Check** before you say OK:

- [ ] No controller and no closure was written: each request is one of these lines.
- [ ] A capability with `webOnly: true` is one that needs the session, signs someone in, or chooses between a page and a
      redirect. Everything else stays a plain capability, so REST and agents can reach it.
- [ ] The form has `method='POST'`, `=csrf()`, and `=methodField('PUT')` or `'DELETE'` for those routes.
- [ ] `success` and `back` point at the pages that show `flash()` and `errors()`.
- [ ] A download names a read-only capability; a webhook has `verify` and its capability is safe to run twice.
- [ ] Sending the form empty shows the messages under the fields, and the typed values stay.

## By hand

Before you start: the Bookshelf tables, the `Book` model and the capabilities `list_books` and `get_book` of
[Routing, steps 1 to 3](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing#definingroutes). The commands run
in the project folder (with Docker: `docker compose exec dev-box php caligrafer.php ...`); the addresses use
`http://localhost:8080`.

1. **Write the capabilities the forms call.** Run:

   ```bash
   docker compose exec dev-box php caligrafer.php service Bookshelf/ListAuthors --scope books:read --read-only
   docker compose exec dev-box php caligrafer.php service Bookshelf/CreateBook --scope books:write
   docker compose exec dev-box php caligrafer.php service Bookshelf/UpdateBook --scope books:write
   docker compose exec dev-box php caligrafer.php service Bookshelf/DeleteBook --scope books:write
   ```

   Replace the content of `application/services/Bookshelf/ListAuthors.php` (the authors of the form's list, and the
   export of step 8) with:

   ```php
   <?php

   use Caligrafy\Capability;
   use Caligrafy\Context;
   use Caligrafy\Service;

   // list_authors: every author, sorted by name. Anyone may read it
   #[Capability(
       name: 'list_authors',
       description: 'Lists the authors of the Bookshelf catalog, sorted by name: id, name and bio.',
       scope: 'books:read',
       readOnly: true,
       public: true
   )]
   class ListAuthors extends Service
   {
       public function handle(array $input, Context $context)
       {
           return Author::query()->orderBy('name')->get();
       }
   }
   ```

   `application/services/Bookshelf/CreateBook.php`:

   ```php
   <?php

   use Caligrafy\Capability;
   use Caligrafy\Context;
   use Caligrafy\Service;

   // create_book: adds a book, with the same rules whoever calls it
   #[Capability(
       name: 'create_book',
       description: 'Adds a book to the Bookshelf catalog and returns it with its id and its author. The author must already exist: use list_authors to find author_id.',
       scope: 'books:write'
   )]
   class CreateBook extends Service
   {
       public $rules = array(
           'title' => 'required|max_len,200',
           'published_year' => 'required|integer|min_numeric,1450|max_numeric,current_year',
           'summary' => 'max_len,2000',
           'author_id' => 'required|integer|exists,authors.id'
       );
       public $filters = array('title' => 'trim', 'summary' => 'trim');
       public $descriptions = array(
           'title' => 'The title of the book',
           'published_year' => 'The year it was first published, for example 1969 (not after this year)',
           'summary' => 'Optional: one or two sentences about the book',
           'author_id' => 'The id of its author (list_authors)'
       );

       public function handle(array $input, Context $context)
       {
           $id = Book::insert($input);   // one INSERT, every value bound; returns the id of the new book
           return Book::with('author')->find($id);
       }
   }
   ```

   `application/services/Bookshelf/UpdateBook.php`:

   ```php
   <?php

   use Caligrafy\Capability;
   use Caligrafy\Context;
   use Caligrafy\Service;
   use Caligrafy\ServiceError;

   // update_book: changes only the inputs that are given
   #[Capability(
       name: 'update_book',
       description: 'Changes the title, year, summary or author of a book of the catalog, by its id. Only the inputs given are changed. Returns the book with its author.',
       scope: 'books:write'
   )]
   class UpdateBook extends Service
   {
       public $rules = array(
           'id' => 'required|integer',
           'title' => 'max_len,200',
           'published_year' => 'integer|min_numeric,1450|max_numeric,current_year',
           'summary' => 'max_len,2000',
           'author_id' => 'integer|exists,authors.id'
       );
       public $filters = array('title' => 'trim', 'summary' => 'trim');
       public $descriptions = array(
           'id' => 'The id of the book to change',
           'title' => 'A new title',
           'published_year' => 'A new year of publication',
           'summary' => 'A new summary',
           'author_id' => 'The id of a new author (list_authors)'
       );

       public function handle(array $input, Context $context)
       {
           if (!Book::find($input['id'])) {
               throw ServiceError::notFound("There is no book #{$input['id']}");
           }
           // keep only the inputs that were given: a missing input never erases a column
           $changes = array();
           foreach (array('title', 'published_year', 'summary', 'author_id') as $field) {
               if (isset($input[$field])) {
                   $changes[$field] = $input[$field];
               }
           }
           // a book always has a title, a year and an author: given empty, they are refused like a missing required input
           $errors = array();
           foreach (array('title' => 'Title', 'published_year' => 'Published Year', 'author_id' => 'Author Id') as $field => $label) {
               if (($changes[$field] ?? null) === '') {
                   $errors[$field] = "The $label field is required";
               }
           }
           if ($errors) {
               throw ServiceError::invalid($errors);
           }
           if ($changes) {
               Book::where('id', $input['id'])->update($changes);   // only this book: an update needs a where
           }
           return Book::with('author')->find($input['id']);
       }
   }
   ```

   `application/services/Bookshelf/DeleteBook.php`:

   ```php
   <?php

   use Caligrafy\Capability;
   use Caligrafy\Context;
   use Caligrafy\Service;
   use Caligrafy\ServiceError;

   // delete_book: destructive, so AI agents ask before calling it
   #[Capability(
       name: 'delete_book',
       description: 'Deletes a book of the catalog, by its id. This cannot be undone.',
       scope: 'books:write',
       destructive: true
   )]
   class DeleteBook extends Service
   {
       public $rules = array('id' => 'required|integer');
       public $descriptions = array('id' => 'The id of the book to delete');

       public function handle(array $input, Context $context)
       {
           // delete() returns how many rows it deleted: 0 when there is no such book
           if (!Book::where('id', $input['id'])->delete()) {
               throw ServiceError::notFound("There is no book #{$input['id']}");
           }
           return array('deleted' => (int) $input['id']);
       }
   }
   ```

2. **Turn on sign-in.** The forms are for signed-in people. Create the `users` table of the authentication module:

   ```bash
   docker compose exec dev-box php caligrafer.php sql application/models/Auth/create_db.sql
   ```

   It prints ` application/models/Auth/create_db.sql run on <your database>`. In
   `application/config/routing/web.php`, remove the `//` in front of `Auth::authentication('User', 'users');`.

3. **Declare the routes.** In `application/config/routing/web.php`, replace the Bookshelf lines of Routing step 4 with
   these, before `Route::run();`:

   ```php
       // sign-in pages: /login, /logout, /register, /notAuthorized
       Route::auth(['home' => '/books']);

       // the Bookshelf pages and their forms
       Route::page('/books', 'Bookshelf/books', ['data' => ['books' => 'list_books']]);
       Route::page('/books/new', 'Bookshelf/new', ['signedIn' => true, 'comeBack' => true, 'data' => ['authors' => 'list_authors']]);
       Route::form('/books', 'create_book', ['success' => '/books/{id}', 'flash' => 'Book added']);
       Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book'], 'notFound' => 'Bookshelf/notfound']);
       Route::form('/books/{id}', 'update_book', ['method' => 'PUT', 'success' => '/books/{id}', 'flash' => 'Saved']);
       Route::form('/books/{id}', 'delete_book', ['method' => 'DELETE', 'success' => '/books', 'flash' => 'Book deleted']);

       // an export and an address that moved
       Route::download('/authors.csv', 'list_authors', ['filename' => 'authors.csv']);
       Route::redirect('/catalog', '/books');
   ```

   `/books/new` comes before `/books/{id}`: the first route that matches wins. `comeBack` sends a visitor to
   `/login?return=/books/new` instead of `/login`, so that signing in lands on the form.

4. **Write the views.** `application/views/Bookshelf/new.pug`, the form that posts to `create_book`:

   ```pug
   extends ../default/master/site

   block content
     section.cq-hero.cq-hero--page
       h1.cq-display New book

     section.cq-band.cq-band--tight
       .cq-inner.cq-inner--narrow
         if flash('error')
           .cq-alert.cq-alert--error(role='alert')= flash('error')
         form(method='POST', action=$home . 'books')
           =csrf()
           .cq-field
             label(for='title') Title
             input#title.form-control(type='text', name='title', value=old('title'))
             if errors('title')
               p.cq-field-error= errors('title')
           .cq-field
             label(for='published_year') Year
             input#published_year.form-control(type='number', name='published_year', value=old('published_year'))
             if errors('published_year')
               p.cq-field-error= errors('published_year')
           .cq-field
             label(for='author_id') Author
             select#author_id.form-select(name='author_id')
               each $a in $authors
                 option(value=$a['id'], selected=$a['id'] == old('author_id'))= $a['name']
             if errors('author_id')
               p.cq-field-error= errors('author_id')
           button.btn.btn-primary(type='submit') Add book
   ```

   Replace `application/views/Bookshelf/book.pug` with the book's page and its forms (edit, cover, delete):

   ```pug
   extends ../default/master/site

   block content
     section.cq-hero.cq-hero--page
       h1.cq-display= $book['title']
       p.cq-lead= 'by ' . $book['author']['name'] . ', ' . $book['published_year']

     section.cq-band.cq-band--tight
       .cq-inner.cq-inner--narrow
         if flash('success')
           .cq-alert.cq-alert--success(role='status')= flash('success')
         if flash('error')
           .cq-alert.cq-alert--error(role='alert')= flash('error')
         form(method='POST', action=$home . 'books/' . $book['id'])
           =csrf()
           =methodField('PUT')
           .cq-field
             label(for='title') Title
             input#title.form-control(type='text', name='title', value=old('title', $book['title']))
             if errors('title')
               p.cq-field-error= errors('title')
           .cq-field
             label(for='published_year') Year
             input#published_year.form-control(type='number', name='published_year', value=old('published_year', $book['published_year']))
             if errors('published_year')
               p.cq-field-error= errors('published_year')
           button.btn.btn-primary(type='submit') Save
         form(method='POST', action=$home . 'books/' . $book['id'] . '/cover', enctype='multipart/form-data')
           =csrf()
           .cq-field
             label(for='cover') Cover (PNG, JPG or WebP, 2 MB at most)
             input#cover(type='file', name='cover', accept='.png,.jpg,.webp')
             if errors('cover')
               p.cq-field-error= errors('cover')
           button.btn.btn-secondary(type='submit') Save the cover
         form(method='POST', action=$home . 'books/' . $book['id'])
           =csrf()
           =methodField('DELETE')
           button.btn.btn-secondary(type='submit') Delete this book
   ```

   Replace `application/views/Bookshelf/books.pug` with the list, its message and a link to the form:

   ```pug
   extends ../default/master/site

   block content
     section.cq-hero.cq-hero--page
       h1.cq-display Books

     section.cq-band.cq-band--tight
       .cq-inner
         if flash('success')
           .cq-alert.cq-alert--success(role='status')= flash('success')
         if $books['total'] == 0
           p.cq-empty-state No books yet.
         else
           ul.cq-rows
             each $book in $books['data']
               li.cq-row
                 a(href=$home . 'books/' . $book['id'])= $book['title']
                 span= ' (' . $book['author']['name'] . ', ' . $book['published_year'] . ')'
         a.btn.btn-primary(href=$home . 'books/new') Add a book
   ```

   The cover form is used in [step 7](#files).

5. **Try the forms in the browser.** Open `http://localhost:8080/books/new`: you are sent to
   `/login?return=%2Fbooks%2Fnew`. Open `http://localhost:8080/register`, create an account (a username, a password
   typed twice), then open `/books/new` again and sign in: you land on the form.

   + On `/books/new`, send the form empty: the page comes back with "Some of the inputs are invalid" at the top and,
     under the fields, "The Title field is required" and "The Published Year field is required" (the list of authors
     always sends one).
   + Type `The Dispossessed` as the title and `2999` as the year: the title stays in its field, and the message is
     "The Published Year field needs to be a numeric value, equal to, or lower than <this year>".
   + Type `The Dispossessed`, `1974` and choose *Ursula K. Le Guin*: you land on `/books/6` with "Book added".
   + Change the title and click **Save**: "Saved". Click **Delete this book**: you land on `/books` with "Book deleted".

6. **Try them with curl.** A form post needs the session cookie and its CSRF token. Run:

   ```bash
   curl -s -c jar.txt -b jar.txt http://localhost:8080/login | grep -o "name='_token' value='[^']*'"
   ```

   It prints `name='_token' value='<token>'`. Sign in with that token:

   ```bash
   curl -s -i -c jar.txt -b jar.txt -X POST http://localhost:8080/login -d "_token=<token>&username=<you>&passcode=<your password>"
   ```

   It answers `302 Found` with `Location: http://localhost:8080/books`. Signing in gives the session a new CSRF token:
   read it again from the form page, then post the form with it:

   ```bash
   curl -s -c jar.txt -b jar.txt http://localhost:8080/books/new | grep -o "name='_token' value='[^']*'"
   curl -s -i -c jar.txt -b jar.txt -X POST http://localhost:8080/books -d "_token=<new token>&title=Wild Seed&published_year=1980&author_id=2"
   ```

   It answers `302 Found` with `Location: http://localhost:8080/books/<new id>`. With the old token, or without
   `_token`, a post answers `403` `[ERROR 3000] Security Error - Cross Site Forgery`.

   The same route answers a script that asks for JSON, with the token in the `X-CSRF-Token` header:

   ```bash
   curl -s -i -c jar.txt -b jar.txt -X POST -H "Accept: application/json" -H "X-CSRF-Token: <token>" \
        -H "Content-Type: application/json" http://localhost:8080/books -d '{"title":"","published_year":1969,"author_id":2}'
   ```

   It answers `422` with
   `{"error":{"code":"invalid","message":"Some of the inputs are invalid","fields":{"title":"The Title field is required"}}}`;
   with a title, `201` and `{"data":{"id":...,"title":...,"author":{...}}}`. Without the header: `403` and
   `{"error":{"code":"forbidden","message":"Missing or invalid CSRF token: send the X-CSRF-Token header"}}`.

7. **Add a file input.** The books need a column for the cover. The table holds data: add it with a
   [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations). Run:

   ```bash
   docker compose exec dev-box php caligrafer.php migrate make add_books_cover
   ```

   It prints ` application/migrations/<number>_add_books_cover.sql written: add its SQL, then php caligrafer.php migrate`.
   Write in that file:

   ```sql
   -- add_books_cover
   ALTER TABLE books ADD COLUMN cover VARCHAR(255) NULL AFTER summary;
   ```

   Run `docker compose exec dev-box php caligrafer.php migrate` (it prints ` OK   <number>_add_books_cover.sql`), and
   add `public $cover;` after `public $summary;` in `application/models/Bookshelf/Book.php`. Then run
   `docker compose exec dev-box php caligrafer.php service Bookshelf/SetCover --scope books:write`, and replace the
   content of `application/services/Bookshelf/SetCover.php` with:

   ```php
   <?php

   use Caligrafy\Capability;
   use Caligrafy\Context;
   use Caligrafy\Database;
   use Caligrafy\Service;

   #[Capability(
       name: 'set_cover',
       description: 'Sets the cover image of a book, by its id. Returns the id and the URL of the cover.',
       scope: 'books:write'
   )]
   class SetCover extends Service
   {
       public $rules = array(
           'id' => 'required|integer|exists,books.id',
           'cover' => 'required|file|extension,png;jpg;webp|max_size,2mb',
       );

       public function handle(array $input, Context $context)
       {
           Database::table('books')->where('id', $input['id'])->update(array('cover' => $input['cover']));
           return array('id' => (int) $input['id'], 'cover' => $input['cover']);
       }
   }
   ```

   Add the route, after the other `Route::form` lines:

   ```php
       Route::form('/books/{id}/cover', 'set_cover', ['success' => '/books/{id}', 'flash' => 'Cover saved']);
   ```

   On a book's page, choose a PNG file and click **Save the cover**: "Cover saved", and the `cover` column of the book
   holds `http://localhost:8080/public/uploads/<24 random characters>.png`. A GIF answers "This type of file is not
   accepted: png, jpg, webp"; a 3 MB PNG "The file is too large (at most 2 MB)"; no file "The Cover field needs a
   file" (2.19.1).

8. **Try the export and the redirect.** Run:

   ```bash
   curl -s -i http://localhost:8080/authors.csv
   ```

   It answers `200` with `Content-Type: text/csv; charset=utf-8`, `Content-Disposition: attachment; filename="authors.csv"`
   and the rows of `list_authors`, the same capability the form's list reads:

   ```text
   id,name,bio,created_at,modified_at
   3,Italo Calvino,"Italian writer of playful, inventive novels and short stories.",2026-11-07 23:10:56,2026-11-07 23:10:56
   2,Octavia E. Butler,"American science fiction author, the first to receive a MacArthur fellowship.",2026-11-07 23:10:56,2026-11-07 23:10:56
   1,Ursula K. Le Guin,"American author of science fiction and fantasy, known for the Earthsea books.",2026-11-07 23:10:56,2026-11-07 23:10:56
   ```

   `curl -s -i http://localhost:8080/catalog` answers `302 Found` with `Location: http://localhost:8080/books`.

9. **Add a sign-up page of your own.** `/register` asks for a username and a password. The page `/join` also asks to
   accept the terms, signs the person in at once, and is for visitors only. In `web.php`, after `Route::auth(...)`:

   ```php
       Route::page('/join', 'Bookshelf/join', ['visitorsOnly' => '/books']);
       Route::form('/join', 'register_user', [
           'visitorsOnly' => '/books',
           'same' => ['confirmpasscode' => ['passcode', 'The two passwords are not the same']],
           'accepted' => ['terms' => 'Accept the terms of use to create an account'],
           'signsIn' => 'id',
           'success' => '/books',
           'back' => '/join',
           'flash' => 'Welcome to the Bookshelf',
       ]);
   ```

   `register_user` is the capability the authentication module ships. It answers the new account, and `'signsIn' => 'id'`
   signs in the person whose id is in that field. Write `application/views/Bookshelf/join.pug`:

   ```pug
   extends ../default/master/site

   block content
     main.cq-auth
       h1 Join the Bookshelf
       if flash('error')
         .cq-alert.cq-alert--error(role='alert')= flash('error')
       form(method='POST', action=$home . 'join')
         =csrf()
         .cq-field
           label(for='username') Username
           input#username.form-control(type='text', name='username', value=old('username'), required)
           if errors('username')
             p.cq-field-error= errors('username')
         .cq-field
           label(for='passcode') Password
           input#passcode.form-control(type='password', name='passcode', required, autocomplete='new-password', maxlength='72')
           if errors('passcode')
             p.cq-field-error= errors('passcode')
         .cq-field
           label(for='confirmpasscode') The same password again
           input#confirmpasscode.form-control(type='password', name='confirmpasscode', required, autocomplete='new-password', maxlength='72')
           if errors('confirmpasscode')
             p.cq-field-error= errors('confirmpasscode')
         .cq-field
           label
             input(type='checkbox', name='terms', value='1')
             |  I accept the terms of use
           if errors('terms')
             p.cq-field-error= errors('terms')
         button.btn.btn-primary(type='submit') Join
   ```

   Sign out and open `http://localhost:8080/join`. Send two different passwords and leave the box empty: the page comes
   back with "Some of the inputs are invalid", "The two passwords are not the same" under the second password and
   "Accept the terms of use to create an account" under the box, and the username is still there. Send the form right: you
   land on `/books`, signed in, with "Welcome to the Bookshelf" (`books.pug` shows `flash('success')`). Open `/join` again:
   you are sent to `/books`.

10. **Answer a request no page or form can say.** When an author has exactly one book, `/authors/{author_id}/books` goes
    straight to that book; otherwise it shows the list. One address, two answers: [a web-only capability](#action). Run
    `docker compose exec dev-box php caligrafer.php service Bookshelf/OpenAuthorBooks` and replace the content of
    `application/services/Bookshelf/OpenAuthorBooks.php` with:

    ```php
    <?php

    use Caligrafy\Capability;
    use Caligrafy\Context;
    use Caligrafy\Service;
    use Caligrafy\Web;

    // open_author_books: one book goes straight to its page, otherwise the list
    #[Capability(
        name: 'open_author_books',
        description: 'Opens the books of an author: the book itself when there is one, otherwise the list.',
        readOnly: true,
        public: true,
        webOnly: true
    )]
    class OpenAuthorBooks extends Service
    {
        public $rules = array('author_id' => 'required|integer');

        public function handle(array $input, Context $context)
        {
            $books = $this->capability('list_books', array('author_id' => $input['author_id']), $context);
            if ($books['total'] == 1) {
                return Web::redirect('/books/' . $books['data'][0]['id']);
            }
            return Web::view('Bookshelf/books', array('books' => $books));
        }
    }
    ```

    In `web.php`:

    ```php
        Route::action('/authors/{author_id}/books', 'open_author_books', ['back' => '/books']);
    ```

    Run:

    ```bash
    curl -s -i http://localhost:8080/authors/3/books | grep -iE "^HTTP|^Location"
    curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/authors/2/books
    curl -s -i http://localhost:8080/authors/abc/books | grep -iE "^HTTP|^Location"
    ```

    They print `HTTP/1.1 302 Found` with `Location: http://localhost:8080/books/5` (Italo Calvino has one book), `200` (the
    list of Octavia E. Butler's two books), and `302` to `/books` (the `back` option), where `flash('error')` says "Some of
    the inputs are invalid". `docker compose exec dev-box php caligrafer.php call open_author_books author_id=3` prints
    `{"error":{"code":"not_found","message":"There is no capability 'open_author_books'"}}`: only the route reaches it.

11. **Receive events from another service.** Webhooks are in [their own section](#webhook), with a complete example.

**Check**

- [ ] `/books/new` sends a visitor to `/login?return=%2Fbooks%2Fnew`, shows the form to someone signed in, and signing in
      from there lands on the form.
- [ ] An empty form comes back with a message under each field; a reload of that page shows no message (they last one
      request).
- [ ] A valid form lands on the new book's page with "Book added"; Save shows "Saved"; Delete lands on `/books` with
      "Book deleted".
- [ ] A post without `_token` answers `403`.
- [ ] `/authors.csv` downloads the rows; `/catalog` redirects to `/books`.
- [ ] `/join` signs a new person in and sends someone already signed in to `/books`.
- [ ] `/authors/3/books` redirects to `/books/5`, and `/authors/2/books` shows a list.
## <a name="form"></a>Forms: `Route::form`

`Route::form($route, $capability, $options)` answers the form's `POST` (or its `PUT` or `DELETE` through `_method`)
by calling the capability with the form's fields, its files and the route variables (the route variables win), as the
person who sent it. The page that shows the form stays a `Route::page`.

| The capability | The person goes to | The next page has |
|---|---|---|
| succeeds | `success`, its `{name}` filled from the result, then from the route variables; without `success`, back to the form | `flash('success')` with the `flash` message |
| refuses the input (`invalid`) or finds a duplicate (`conflict`) | back: the `back` option, else the page it came from (the `Referer`, when it is a page of this site), else `/` | `errors('title')`, `old('title')`, `flash('error')` |
| needs someone signed in, nobody is | the sign-in page (`signIn`, default `/login`); without the authentication module, `403` | |
| refuses the person (`forbidden`) | `403` `[ERROR 1006] Forbidden` | |
| finds nothing, or anything else | `404` `[ERROR 1005] Page Not Found` | |

| Option | Default | What it does |
|---|---|---|
| `method` | `'POST'` | `'PUT'`, `'DELETE'`, or a list (`['POST', 'PUT']`); `GET` is refused (pages are `Route::page`) |
| `success` | back to the form | a path with `{placeholders}`, or `function ($result) { return '/books/' . $result['id']; }` |
| `flash` | none | the message for `flash('success')`, with `{placeholders}` as in `success`; or `['key' => 'message']` |
| `back` | the `Referer` of this site, else `/` | where invalid input goes, with the route's `{placeholders}`: `'back' => '/books/{id}'` |
| `error` | the capability's message | your message for `flash('error')`, or `['key' => 'message']` |
| `signIn` | `'/login'` | where a visitor goes when the capability needs someone |
| `visitorsOnly` | none | a path: people already signed in are sent there and the capability does not run; a JSON request gets `403` |
| `same` | none | fields that must match: `['password_again' => ['password', 'The two passwords are not the same']]`; without a message, "The two values are not the same" |
| `accepted` | none | boxes that must be ticked: `['terms' => 'Accept the terms of use']` |
| `inputs` | none | values only the server sets: an array, or `function ($input) { return [...]; }`. They replace what the form sent; the route variables still win |
| `signsInWith` | `'password'` | how `signsIn` signed the person in, for `AuthRoutes::signedInBy()` (2.21.7) |
| `signsIn` | none | the field of the capability's answer that holds the id of the person to sign in: `'signsIn' => 'id'`. A new session id and a new CSRF token, as for `Route::auth`. It records no way of signing in: `AuthRoutes::signedInBy()` answers `null` for that session |

The last five options arrived in 2.20.0.

**The order of the checks.** `visitorsOnly`, then (JSON with the session) the CSRF header, then `same` and `accepted`,
then the capability. A form that breaks `same` or `accepted` never reaches the capability, and their messages arrive in
`errors('password_again')`, like the capability's. Both are read from what the person sent: declare `password_again` in
`$rules` only if the capability needs it.

**Values the form must not choose.** A form can send any field. `inputs` writes the ones only the server knows, over
anything the form sent: the address a payment page comes back to, the visitor's address, today's price.

**A form that leaves the site.** `success` can be a full `https://` address, or a function that returns one: that is how a
form leaves for a payment page.

```php
Route::form('/orders/{order}/pay', 'start_checkout', [
    'inputs' => fn () => ['site' => session('home')],
    'success' => fn ($result) => $result['url'],
    'back' => '/orders',
]);
```

**A form that signs someone in.** `signsIn` is for a capability that creates or finds the person, and answers their id:
sign-up, an invitation link, a confirmation code. The form that decides how to sign in, or a sign-in with a state to
check, is a [`Route::action`](#action).

+ **The CSRF token** of the form (`=csrf()`) is checked as for every form (`403` `[ERROR 3000]` without it).
+ **One request only.** The errors, the old values and the messages are read by the next page, then gone: point
  `success` and `back` at the page that shows them. Passwords, card numbers, tokens (any field whose name contains
  `pass`, `secret`, `token`, `card`, `cvc`, `cvv` or `iban`), files and `_` fields are never kept for `old()`.
+ **A placeholder with no value** (`'success' => '/authors/{author}'` when neither the result nor the route has
  `author`) stops with an error that names it.
+ **JSON**: a request with `Accept: application/json` gets the REST answer instead of redirects: `{"data": ...}` with
  `201` (a `POST` that changes data) or `200`, or `{"error": ...}` with `401`, `403`, `404`, `409` or `422`. With the
  session cookie it needs the `X-CSRF-Token` header.
+ `flash('saved', 'Your changes are saved')` in your own code keeps a message for the next request too.

The view helpers are described in [Views: forms](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#formhelpers):
`errors()` (all the messages), `errors('title')` (one field's, or `null`), `old('title', $default)`, `flash('success')`.
## <a name="files"></a>File inputs: the `file` rule

A capability declares a file input with the rule `file`, an allow-list and a maximum size:

```php
public $rules = array('cover' => 'required|file|extension,png;jpg;webp|max_size,2mb');
```

+ **Web pages (`Route::form`) and REST (`Route::capability`, `Route::capabilities`)** take the file from the request
  once the caller is allowed to call the capability, check it (one file, the allow-list, the size), save it in
  `public/uploads/` under a new random name (the name the browser sent is never used) and give `handle()` its public
  **URL**, a string. A text sent in that field is dropped. When the capability fails, the saved file is deleted.
+ `extension,png;jpg` lists the types allowed; without it, the default list of `uploadFile()` applies (images,
  documents, audio, video, `zip`, `json`). Scripts and markup (`php`, `phtml`, `phar`, `html`, `js`, `svg`...) are
  always refused.
+ `max_size` takes a number of bytes or `kb`, `mb`, `gb` (`500kb`, `1.5mb`). The size limits of PHP
  (`upload_max_filesize`, `post_max_size`) still apply first.
+ **AI agents (MCP) and the command line** cannot send a file: they send a URL or a path, whose extension is checked.
  Never open it without checking where it points.
+ The form needs `enctype='multipart/form-data'`. `required|file` and `required_file` both make the file required, on
  every channel: no file, URL or path answers "The Cover field needs a file", and the input schema of MCP and
  `GET /capabilities` lists the field in `required` (2.19.1; in 2.19.0 `required_file` alone was ignored).
+ `Route::action` passes the files of the request too: a web-only capability with a `file` rule gets the URL.
## <a name="auth"></a>Sign-in: `Route::auth`

```php
Auth::authentication('User', 'users');
Route::auth(['home' => '/books']);
// a users table with an email column: people sign in with it, and are signed in right after signing up
Route::auth(['home' => '/books', 'identifier' => 'email', 'signInAfterRegister' => true]);
```

This declares `GET`/`POST /login`, `GET`/`POST /logout`, `GET`/`POST /register` and `GET /notAuthorized`, with the
views of the authentication module (`application/views/Auth/login.pug`, `register.pug`).

| Option | Default | What it does |
|---|---|---|
| `home` | `'/'` | where people go after signing in (a signed-in person who opens `/login` goes there too) |
| `logout` | `'/'` | where people go after signing out |
| `register` | `true` | `true`: `/register` with the `register_user` capability; `false`: no sign-up; a capability name: yours |
| `identifier` | `'username'` | the `users` column people sign in with, and the name of the sign-in field (`'email'`) |
| `signInAfterRegister` | `false` | `true`: a new account is signed in and goes to `home` instead of the sign-in page |
| `attemptsPerUser` | `0` (off) | failed sign-ins of one username from any address before it is locked (2.19.6) |
| `level` | `0` | the lowest permission level that may sign in (2.19.5): below it, a sign-in is refused like a wrong password |
| `messages` | human words | what sign-in and sign-up say: `invalid`, `locked` (2.19.3, `{minutes}` is the wait), `mismatch`, `register_invalid`, `register_taken`, `registered` (2.19.4); the defaults are `AuthRoutes::MESSAGES` |
| `attempts`, `lock` | `5`, `900` | failed sign-ins per username and address before a `429`, and the window in seconds |
| `views` | `['login' => 'Auth/login', 'register' => 'Auth/register']` | your own views |
| `prefix` | `''` | `'/account'` gives `/account/login`... (the shipped views post to `/login`: write your own) |
| `passkeys` | `false` | `true` adds `POST /passkey/register/options`, `/passkey/register`, `/passkey/login/options`, `/passkey/login` |

+ Signing in and signing out give the person a new session id and a new CSRF token.
+ The fifth failed sign-in for a username from one address within 15 minutes, and every one after it until the 15
  minutes end, answers `429` "Too many tries in a row. For your security, wait 15 minutes, then try again." (2.19.3; the `messages` option sets your own words).
+ A JSON request with `X-CSRF-Token` gets `200` `{"data":{"user":{"id":1,"username":"ada","permissions":0}}}`, `401`
  or `429` in JSON: a Vue app signs in with the same routes.
+ Sign-up sends the register capability every input its `$rules` declare; nothing else of the form reaches it.
+ After signing in, a person goes to `home`, or to the page named by `/login?return=/books/3` (2.20.0). Only a path of
  this site is followed: another site, or `//evil.example`, is ignored and the person goes to `home`. `Route::page` and
  `Route::action` with `'comeBack' => true` build that address for you. A person already signed in who opens that address
  goes straight to the page.
+ Not in `Route::auth`: password reset and face sign-in. `'reset' => true` or `'face' => true` stops with an error. They
  are declared with the other routes: [password reset](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#passwordreset) is
  `Route::page` and `Route::form`, [face sign-in](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition#face-login)
  is `Route::action`.

+ **Sign in with an email.** The simplest way keeps the `users` table: the `username` column holds the lower-cased address.
  [Signing in with an email](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#emailsignin) has the
  steps. `'identifier' => 'email'` is for a table with a separate `email` column.
+ **How a session signed in.** `Route::auth` records `password` or `passkey`, and `AuthRoutes::signedInBy()` reads it (2.21.3).
  A face alone must not change how an account signs in:
  [How a session signed in](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#signedinby).

Everything about users, levels and the sign-in views:
[https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#routeauth).
## <a name="webhook"></a>Webhooks: `Route::webhook`

A payment provider, a library service or GitHub posts events to an address of yours. `Route::webhook` checks that the
event comes from them (its signature), then calls a capability with it. There is no session and no CSRF token: the
signature is the only proof.

1. **A table that remembers the events.** The Bookshelf database already holds data: add the table with a
   migration. Run `docker compose exec dev-box php caligrafer.php migrate make create_webhook_events`, and write in the
   file it names (`application/migrations/<number>_create_webhook_events.sql`):

   ```sql
   -- create_webhook_events
   CREATE TABLE IF NOT EXISTS webhook_events (
       id INT UNSIGNED NOT NULL AUTO_INCREMENT,
       event_id VARCHAR(100) NOT NULL,
       type VARCHAR(100) NOT NULL,
       created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
       PRIMARY KEY (id),
       UNIQUE KEY uq_webhook_events_event_id (event_id)
   ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
   ```

   Run `docker compose exec dev-box php caligrafer.php migrate`. It prints ` OK   <number>_create_webhook_events.sql`.

2. **The capability.** Run `docker compose exec dev-box php caligrafer.php service Bookshelf/RecordEvent`, and replace the content of
   `application/services/Bookshelf/RecordEvent.php` with:

   ```php
   <?php

   use Caligrafy\Capability;
   use Caligrafy\Context;
   use Caligrafy\Database;
   use Caligrafy\Service;
   use Caligrafy\ServiceError;

   #[Capability(
       name: 'record_event',
       description: 'Records an event that the library service posts (its id and type), once per event id.'
   )]
   class RecordEvent extends Service
   {
       public $rules = array('event' => 'required');

       public function handle(array $input, Context $context)
       {
           // only the webhook route may record events: REST, MCP and pages would let a signed-in user make one up
           if ($context->actorType() !== 'webhook') {
               throw ServiceError::forbidden('Only the library service sends events');
           }
           $event = $input['event'];
           if (!is_array($event) || empty($event['id']) || empty($event['type'])) {
               throw ServiceError::invalid(array('event' => 'The event needs an id and a type'));
           }
           // the sender posts an event again until it gets a 2xx: record each id once
           if (!Database::table('webhook_events')->where('event_id', $event['id'])->exists()) {
               Database::table('webhook_events')->insert(array('event_id' => $event['id'], 'type' => $event['type']));
           }
           return array('recorded' => $event['id']);
       }
   }
   ```

3. **The secret and the route.** Add the secret the sender gave you to `.env` (a placeholder here):

   ```text
   LIBRARY_WEBHOOK_SECRET=whsec_test_library
   ```

   In `application/config/routing/web.php`, before `Route::run();`:

   ```php
       // the library service signs each event: X-Signature: sha256=<HMAC-SHA256 of the body with the secret>
       Route::webhook('/hooks/library', 'record_event', ['verify' => function ($rawBody, $headers) {
           $expected = 'sha256=' . hash_hmac('sha256', $rawBody, (string) getenv('LIBRARY_WEBHOOK_SECRET'));
           return hash_equals($expected, $headers['x-signature'] ?? '');
       }]);
   ```

4. **Post a signed event.** Run:

   ```bash
   BODY='{"id":"evt_1","type":"loan.returned"}'
   SIG="sha256=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac whsec_test_library -r | cut -d' ' -f1)"
   curl -s -i -X POST -H "Content-Type: application/json" -H "X-Signature: $SIG" http://localhost:8080/hooks/library -d "$BODY"
   ```

   It answers `200` with `{"received":true}`, and `webhook_events` has one row (`evt_1`, `loan.returned`). The same
   post again answers `200` and adds nothing. With `-H "X-Signature: sha256=bad"`: `400` and
   `{"error":{"code":"invalid_signature","message":"The signature is not valid"}}`. A `GET` answers `405`.

| The event | The answer |
|---|---|
| signature checked, capability done | `200 {"received": true}` |
| bad or missing signature | `400 {"error":{"code":"invalid_signature",...}}` |
| a body that is not JSON | `400 {"error":{"code":"invalid","message":"The body is not JSON"}}` |
| the capability refuses (`ServiceError`) | its status and its error (`422` for `invalid`) |
| no secret set, no such capability, an error in the capability | `500`; the message goes to the PHP error log |

**Stripe.** `'verify' => 'stripe'` checks the `Stripe-Signature` header with the Stripe library:

```php
Route::webhook('/stripe/events', 'record_event', ['verify' => 'stripe']);   // STRIPE_WEBHOOK_SECRET=whsec_... in .env
```

| Option | Default | What it does |
|---|---|---|
| `verify` | required | `'stripe'`, or `function (string $rawBody, array $headers): bool` (header names in lower case; only `true` passes) |
| `secret_env` | `'STRIPE_WEBHOOK_SECRET'` | the `.env` variable that holds the endpoint's signing secret (`whsec_...`, not the API key) |
| `secret` | none | the secret itself, instead of the variable (tests) |
| `tolerance` | `300` | how many seconds old a Stripe signature may be |

+ `verify` is required: a webhook without it stops with an error when `web.php` runs.
+ The body must be JSON; the capability gets `['event' => the decoded body]`, so declare `$rules = ['event' => 'required']`.
+ The capability runs as the system, with full access (the audit log shows `webhook /hooks/library`): treat the event
  as data from outside. Before trusting an amount, ask the provider again
  ([Stripe](https://github.com/caligrafy/caligrafy-quill/wiki/9.2-Stripe-&-Cryptocurrency-Payment#webhook)).
+ Services post an event again until they get a `2xx`: make the capability safe to run twice, as above.
## <a name="download"></a>Downloads: `Route::download`

```php
Route::download('/authors.csv', 'list_authors', ['filename' => 'authors.csv']);
Route::download('/books.json', 'list_books', ['as' => 'json']);   // a page of list_books, ?page=2 for the next
Route::download('/photos.zip', 'list_photo_files', ['as' => 'zip', 'root' => 'public/uploads/photos']);   // 2.22.0
```

| Option | Default | What it does |
|---|---|---|
| `as` | `'csv'` | `'csv'`, `'json'` (pretty-printed) or `'zip'` (the files the capability lists, 2.22.0); anything else stops with an error when `web.php` runs |
| `root` | `'public/uploads'` | for `zip`: the folder of the project the files are read from; a file outside it is never sent. A `root` with `..` stops with an error when `web.php` runs |
| `columns` | the first row's keys | the header row and its order, written even when there is no row: `['title', 'year']` (2.19.5) |
| `filename` | `<capability>.<as>` (`.zip` for a ZIP) | a name, or `function ($result, $input) { return 'books-' . date('Y-m-d') . '.csv'; }` |
| `bom` | `false` | `true` starts the CSV with a UTF-8 BOM (Excel) |
| `formulas` | `false` | `true` keeps cells that start with `=`, `+`, `-`, `@` as they are |
| `signIn` | `'/login'` | where a visitor goes when the capability needs someone |

+ The capability must be read-only (opening a link must not change data). It gets the query string and the route
  variables (`/books.csv?author_id=2`) as the person who opens the link. Refusals are those of `Route::page`: a
  visitor goes to sign in, `403`, or `404`. An input to fix (`?author_id=abc`) answers `422` with the capability's
  error as JSON, as REST does (2.19.5; before, `404`).
+ **CSV**: the header row comes from the `columns` option, else from the first row's columns (then an empty result is
  an empty file), values are quoted where needed (RFC 4180, lines end with
  CRLF), UTF-8. A text cell that starts with `=`, `+`, `-`, `@` or a tab gets a `'` first, so a spreadsheet does not
  run it as a formula. Arrays in a cell are written as JSON, booleans as `true` / `false`.
+ **The columns are the keys of the first row.** A model query returns models, and a model carries every one of its
  properties: `Book::query()->select('id', 'title')->get()` exports `id`, `title` and every other column of `Book`,
  empty. Return arrays for a narrow export: `Database::table('books')->select('id', 'title')->get()` or
  `Book::query()->select('id', 'title')->arrays()->get()`. A related row (`with('author')`) is one cell, in JSON.
+ Each row of the list the capability returns is a line. A `paginate()` page exports its rows (that page only: return
  `get()` to export every row); a single record gives one line.
+ The answer carries `Cache-Control: private, no-store` and `X-Content-Type-Options: nosniff`.

### <a name="zip"></a>Many files as one ZIP (2.22.0)

The capability lists the files; `Route::download` puts them in one archive and sends it. The capability stays plain
data, so the same list also reaches REST, the JS client and agents (who get the names, not the files).

```php
#[Capability(name: 'list_photo_files', description: 'The files of the photos, oldest first', scope: 'photos:read', level: 1, readOnly: true)]
class ListPhotoFiles extends Service
{
    public function handle(array $input, Context $context)
    {
        return array_map(fn ($photo) => [
            'file' => $photo['image'],                                        // relative to 'root'
            'name' => 'pictures/' . date('Y-m-d_H-i-s', strtotime($photo['created_at'])) . '.jpg',   // in the archive
        ], Photo::query()->arrays()->select('image', 'created_at')->orderBy('created_at')->get());
    }
}
```

```php
Route::download('/photos.zip', 'list_photo_files', ['as' => 'zip', 'root' => 'public/uploads/photos',
    'filename' => fn ($files, $input) => 'photos-' . date('Y-m-d') . '.zip']);
```

+ **Each item** is a path (the file keeps its own name) or `['file' => path, 'name' => 'folder/name.jpg']`. Paths are
  relative to `root`; a `paginate()` page gives its rows.
+ **Only files under `root` go in.** A path that leaves it (`../../.env`), a folder, or a file that is missing is left
  out without an error, so a row whose file was deleted does not stop the download. Names are cleaned (no `..`, no
  leading `/`), and a name used twice becomes `name (2).jpg`.
+ **No file at all answers `404`** (the missing page). Hide the link when there is nothing to download, or throw
  `ServiceError::notFound('No photo yet')` in the capability.
+ **Images, video, audio and archives are stored as they are; other files are compressed.** The archive is written to
  a temporary file, sent with its `Content-Length`, then removed: a large export never sits in memory.
+ It needs PHP's **zip** extension: Caligrafy's Docker images and Caligrafy Cloud have it. `Download::archive($files,
  ['root' => ...])` builds the same archive in a test (`['path', 'count', 'names']`; remove `path` afterwards).
## <a name="redirect"></a>Redirects: `Route::redirect`

```php
Route::redirect('/catalog', '/books');                   // 302
Route::redirect('/old/books/{id}', '/books/{id}', 301);  // moved for good
```

+ A `GET` that sends the visitor elsewhere, without a closure. `{name}` in the target takes the route variable of
  the same name (url-encoded); the query string never fills it (`/old/books/2?x=1` goes to `/books/2`).
+ The target is a path of the site or a full `https://` address. The status is `301`, `302` (default), `303`, `307`
  or `308`; anything else, or an empty target, stops with an error when `web.php` runs.
+ `Route::redirect($from, $to, $status, ['keepQuery' => true])` (2.20.0) takes the query string along:
  `/old?page=2` goes to `/new?page=2`. A `#fragment` of the target stays last.
+ A redirect that depends on who asks, or on the data, is a [`Route::action`](#action).
## <a name="action"></a>Everything else: `Route::action`

`Route::page` shows a view and `Route::form` calls a capability and redirects. A few requests are neither: a sign-in
between two sites, a page that chooses between a view and a redirect, a gate, a page that creates a payment. Since
2.21.0 they are capabilities too, declared `webOnly: true` and served by one line. The controller of a new application
is gone: this replaces it.

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;
use Caligrafy\Web;

#[Capability(
    name: 'open_author_books',
    description: 'Opens the books of an author: the book itself when there is one, otherwise the list.',
    readOnly: true,
    public: true,
    webOnly: true
)]
class OpenAuthorBooks extends Service
{
    public $rules = array('author_id' => 'required|integer');

    public function handle(array $input, Context $context)
    {
        $books = $this->capability('list_books', array('author_id' => $input['author_id']), $context);
        if ($books['total'] == 1) {
            return Web::redirect('/books/' . $books['data'][0]['id']);
        }
        return Web::view('Bookshelf/books', array('books' => $books));
    }
}
```

```php
Route::action('/authors/{author_id}/books', 'open_author_books', ['back' => '/books']);
Route::action('/unlock/{name}', 'unlock_shelf', ['method' => 'POST']);
Route::action('/shelf/report', 'shelf_report', ['level' => 1, 'comeBack' => true]);
```

| Option | Default | What it does |
|---|---|---|
| `method` | `'GET'` | `'POST'`, `'PUT'`, `'DELETE'`, or a list (`['GET', 'POST']`) |
| `signedIn`, `level` | none | as in `Route::page`: visitors go to `/login`, people below the level to `/notAuthorized` |
| `comeBack` | `false` | with `signedIn` or `level`, or when the capability needs someone: visitors go to `/login?return=<this page>` |
| `visitorsOnly` | none | a path: people already signed in are sent there |
| `back` | the `Referer` of this site, else `/` | where invalid input or a conflict goes, with the route's `{placeholders}` |
| `error` | the capability's message | your message for `flash('error')` |
| `signIn` | `'/login'` | where a visitor goes when the capability needs someone (`comeBack` replaces it) |

**What it answers.** A `Caligrafy\Web`, or plain data, which is sent as JSON.

| The capability returns | The browser gets |
|---|---|
| `Web::view('Bookshelf/book', $data, $status = 200)` | a Pug view, with `$authorized` and `$user` as on `Route::page` (`$data` wins). A request that asks for JSON gets the data as JSON |
| `Web::redirect('/books', $status = 302)` | a redirect: a path of this site or a full `http(s)` address |
| `Web::json($data, $status = 200)` | JSON, the data as it is, with no `{"data": ...}` around it |
| `Web::text($body, $status = 200)` | the text as it is |
| any of them `->header('Cache-Control', 'no-store')` | one more response header |
| plain data (an array, a model) | JSON, as with `Web::json` |

**When it refuses.** A capability that answers a refusal itself returns a `Web`. One that throws a `ServiceError` gets the
answers of `Route::form`:

| It throws | A browser | A JSON request |
|---|---|---|
| `invalid` or `conflict` | back (`back`, the `Referer`, or `/`) with `errors()`, `old()`, `flash('error')` | `422` or `409` and the REST error |
| `unauthenticated` | the sign-in page (`comeBack`: and back here) | `401` |
| `forbidden` | `403` `[ERROR 1006]` | `403` |
| `not_found` or anything else | `404` `[ERROR 1005]` | `404` |

**What it receives.** The inputs its `$rules` declare, from the form, the JSON body or the query string, and the route
variables. Its files are saved and given as URLs, as for `Route::form`. It runs as the person who sent the request, with
its `public`, `scope` and `level` checks, its validation and its audit log, like any capability.

> The route variables win over the query string and the form, as on `Route::page` and `Route::form`: `/books/3?id=9` gives
> `id = 3` (2.21.2; in 2.21.0 and 2.21.1 the query string replaced them here and in `Route::capability`). When a route
> variable decides what is reached, still check that the person may open that row.

### <a name="webonly"></a>What a web-only capability may do

The rule of the framework still holds: **only capabilities touch models**. A web-only capability is a capability. What
sets it apart is what it may do besides:

| A plain capability | A web-only capability |
|---|---|
| returns data, or refuses | may also return a view, a redirect, JSON or text |
| never reads the session or the request: `$context` says who calls | may read `session()`, `request()`, `$_SERVER`, `$_COOKIE` |
| never signs anyone in | may sign people in and out |
| on a page, only `readOnly` | a `GET` may change data |
| reached by REST, MCP, the JS client, the command line, `Route::page`, `Route::form`, `$this->call()` | reached by **`Route::action` only** |

That last line is the price. Everywhere else it answers `not_found` "There is no capability", it is left out of
`GET /capabilities`, MCP and `php caligrafer.php capabilities`, and `Route::page`, `Route::form` or `Route::download` on it
fail. So keep the work that several channels share in plain capabilities, and call them from the web-only one:

```php
$books = $this->capability('list_books', array('author_id' => 2), $context);   // as the same person, with its rules
```

`$this->capability()` runs the other capability with its checks, validation and audit, and throws its `ServiceError`.

**Signing someone in.** For a page that leaves or reloads, `Caligrafy\AuthRoutes::signIn($user, null, 'partner')`: a new
session id, a new CSRF token and how it signed in (the third argument, 2.21.3, read by `AuthRoutes::signedInBy()`). For a page
that stays open and keeps sending JSON, `session_regenerate_id(true); Auth::authorize($user); AuthRoutes::rememberSignIn('face');`:
the page keeps its token. `$context` was built before the sign-in and does not change: to call a capability as the person
just signed in, build a new one with `Context::fromRequest(request(), 'web')`.

**CSRF and JSON.**

+ A form's `POST`, `PUT` or `DELETE` needs its `_token` (`=csrf()`), as for every form: `403` `[ERROR 3000]` without it.
+ A JSON call (`Accept: application/json`), `GET` included, needs the page's `X-CSRF-Token` header (`apiHeaders()` of the
  Vue apps) or, with `Auth::activateAPI();` in `web.php` (the template has it), a token that grants everything
  (`--scopes "*"`), signed in or not: `401` `[ERROR 1004]` without it (2.21.1). A scoped token is refused: programs use the
  capability routes.
+ A plain `GET` opened by a link has no token. A `GET` that changes data can be triggered by a link on another site: keep
  it to what is harmless when that happens, and use `'method' => 'POST'` with a form for the rest.

**Tests.** `$this->action('open_author_books', ['author_id' => 3], $user)` calls it as `Route::action` does and returns
what it answered; `->describe()` gives `type`, `target`, `data`, `status` and `headers`. `$this->call()` answers
`not_found`, as every other channel does. See [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App#helpers).

**The data routes of the Watson bot apps** are one line too: `Route::bots();`.
## <a name="controller"></a>Do you still need a controller?

No. With `Route::page`, `Route::form`, `Route::auth`, `Route::webhook`, `Route::download`, `Route::redirect`,
`Route::action` and the capability routes, every request is declared, and an application can have no controller at all.
Existing controllers keep working and can stay:
[Controllers](https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers) shows how to move one when you want to. Never write data in a closure route
(`Route::post('/x', function () {...})`): it has no permission rules and no CSRF check for JSON calls.

| The request | Declare it with |
|---|---|
| A view, with data from read-only capabilities | `Route::page` |
| A form that calls one capability, then redirects | `Route::form` |
| Sign-in, sign-out, sign-up pages | `Route::auth` |
| A confirmation or sign-up that signs someone in | `Route::form` with `signsIn` |
| Events another service posts | `Route::webhook` |
| A file, or many files as one ZIP | `Route::download` |
| An address that moved | `Route::redirect` |
| Data for programs, the JS client, agents | `Route::capability`, `Route::capabilities`, `Route::mcp` |
| Different answers for one address, the session, a sign-in of your own, a page that creates a payment | `Route::action` |
## Common mistakes

+ **`success` redirects to a page that redirects again**: the message is read by the page in between and lost. Point
  `success` and `back` at the page that shows it.
+ **A JSON post with the session and no `X-CSRF-Token`** answers `403`: send the header (`apiHeaders()` in the Vue
  apps).
+ **`/books/new` declared after `/books/{id}`**: `/books/new` shows the *Not found* page with "Some of the inputs are
  invalid" (`get_book` refuses the id `new`).
+ **A file form without `enctype='multipart/form-data'`**: no file arrives, and the form comes back with "The Cover
  field needs a file".
+ **`'verify' => 'stripe'` without `STRIPE_WEBHOOK_SECRET`**: every event answers `500`. Use the endpoint's
  `whsec_...`, not the `sk_...` key.
+ **A webhook capability that is not idempotent**: a retried event is recorded twice.
+ **A download of a capability that writes**: `Route::download` refuses it when the link is opened.
+ **A ZIP whose files live outside `root`**: they are left out, and an empty list answers `404`. Give the folder that
  holds them, relative to the project (`public/uploads/photos`), and paths relative to it.
+ **`Route::action` on a capability without `webOnly: true`**, or `webOnly: true` behind `Route::page`, `Route::form` or
  REST: the first stops with an error that names it, the others answer "There is no capability".
+ **A web-only capability for work other channels need**: agents and programs cannot reach it. Put the work in a plain
  capability and call it with `$this->capability()`.
+ **A JSON call to `Route::action` without `X-CSRF-Token`**: `401` `[ERROR 1004]`, even for a `GET` and for a visitor. Send
  `apiHeaders()`.
+ **`AuthRoutes::signIn()` on a page that stays open**: it gives the session a new CSRF token, and the page's next JSON call
  answers `401`. Use `session_regenerate_id(true); Auth::authorize($user);` there.
+ **`comeBack` with a `return=` you build by hand to another site**: it is ignored, the person goes to `home`.

## Related pages

+ [Routing](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing): `Route::page` and how routes match
+ [Validation](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation): the rules of `$rules`, `exists`, `unique`, `file`
+ [Views: forms](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#formhelpers): `errors()`, `old()`, `flash()`
+ [Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#routeauth): `Route::auth` in depth
+ [Stripe & cryptocurrency payment](https://github.com/caligrafy/caligrafy-quill/wiki/9.2-Stripe-&-Cryptocurrency-Payment#webhook)
+ [Controllers](https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers): what existing controllers do, and how to move one
+ [Release notes 2.19.0](https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.19.0), [2.20.0](https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.20.0), [2.21.0](https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.21.0)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Route-Page -->

# Pages: `Route::page`

`Route::page($route, $view, $options)` answers a `GET` with a Pug view, through the framework's page controller. The
page gets its data from **read-only capabilities**, never from models: the same capabilities REST, the JS client and
AI agents call. Since 2.5.0; `visitorsOnly`, `comeBack` and `query` since 2.20.0, `query` defaults since 2.21.0.

```php
Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book'], 'notFound' => 'Bookshelf/notfound']);
```
## With Claude

```text
/caligrafy-quill:new-capability get_book books:read read-only public: one book with its author, shown at /books/{id}
```

Claude writes the capability in `application/services/<Folder>/`, the `Route::page` line in
`application/config/routing/web.php` and the Pug view in `application/views/`.

**Check** before you say OK:
+ the page's `data` names read-only capabilities only;
+ fixed addresses (`/books/new`) are declared before the ones with a variable (`/books/{id}`);
+ `/books/abc` and `/books/999` show the `notFound` view with a `404`, not a `500`.
## By hand

Before you start: the Bookshelf tables, the `Book` model and the capabilities `list_books` and `get_book` of
[Routing, steps 1 to 3](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing#definingroutes).

1. **Declare the pages.** In `application/config/routing/web.php`, before `Route::run();`:

   ```php
       Route::page('/books', 'Bookshelf/books', ['data' => ['books' => 'list_books']]);
       Route::page('/books/new', 'Bookshelf/new', ['signedIn' => true, 'comeBack' => true]);
       Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book'], 'notFound' => 'Bookshelf/notfound']);
   ```

   `/books/new` comes before `/books/{id}`: the first route that matches wins.

2. **Write the view.** `application/views/Bookshelf/books.pug` reads `$books`, the result of `list_books` (a page of
   `paginate()`: `data` and `total`), as plain arrays:

   ```pug
   extends ../default/master/site

   block content
     section.cq-hero.cq-hero--page
       h1.cq-display Books

     section.cq-band.cq-band--tight
       .cq-inner
         if $books['total'] == 0
           p.cq-empty-state No books yet.
         else
           ul.cq-rows
             each $book in $books['data']
               li.cq-row
                 a(href=$home . 'books/' . $book['id'])= $book['title']
                 span= ' (' . $book['author']['name'] . ', ' . $book['published_year'] . ')'
   ```

   Pug in Caligrafy is PHP: strings are joined with `.`, never `+`.

3. **Open it.** `http://localhost:8080/books` lists the books, `/books/3` shows one, `/books/abc` shows the
   `notFound` view with a `404` (`get_book`'s `integer` rule refuses `abc`).
## <a name="options"></a>Options

| Option | Default | What it does |
| --- | --- | --- |
| `data` | none | `name => 'capability'`: calls each capability as the person who opens the page and gives the result to the view as `$name`. Its inputs are the query string and the route variables; the route variables win (`/books/3?id=9` gives `id = 3`). `name => ['capability', ['author_id' => 2]]` gives fixed inputs instead. Only read-only capabilities |
| `signedIn` | `false` | `true`: visitors are sent to `/login` |
| `level` | `0` | people whose level (the `permissions` column of `users`) is lower are sent to `/notAuthorized`, visitors to `/login` |
| `comeBack` | `false` | `true`, with `signedIn` or `level`, or when a `data` capability needs someone: visitors go to `/login?return=<this page, with its query string>`, and `Route::auth` brings them back after signing in (2.20.0) |
| `visitorsOnly` | none | a path: people already signed in are sent there (a sign-up or landing page) (2.20.0) |
| `query` | none | what the view gets of the query string: `['show']` gives `$show`, `''` when absent (2.20.0); `['app' => 'index']` gives `$app`, `'index'` when absent (2.21.0). A route variable of the same name wins |
| `with` | none | fixed values for the view: `['with' => ['title' => 'Books']]` |
| `notFound` | none | a view shown with a `404` when a `data` capability refuses (not found, or inputs it refuses). It gets the route variables, the `with` values, `$message`, `$authorized` and `$user` |

`signedIn`, `level` and `visitorsOnly` need `Auth::authentication('User', 'users');` in `web.php`; without it, opening
the page stops with an error that says so.

More examples, each one line:

```php
Route::page('/', 'default/index');
Route::page('/admin/books', 'Bookshelf/admin', ['level' => 1, 'data' => ['books' => 'list_books']]);
Route::page('/about', 'default/about', ['with' => ['title' => 'About the Bookshelf']]);
Route::page('/join', 'Bookshelf/join', ['visitorsOnly' => '/books']);
Route::page('/books', 'Bookshelf/books', ['data' => ['books' => 'list_books'], 'query' => ['sort' => 'title']]);
Route::page('/apps/{appName}', 'Client/app', ['query' => ['app' => 'index']]);   // a Vue, bot or ML app
```
## <a name="view"></a>What the view receives

+ the route variables (`$id`), the names listed in `query`, the `with` values;
+ the `data` results, as plain arrays (`$book['title']`, `$book['author']['name']`);
+ `$authorized` (true when someone is signed in) and `$user` (`id`, `username`, `permissions`, or `null`).

The rest of the query string stays out of the view: a `data` capability gets it as inputs. `authorized` and `user` are
reserved names: a `data`, `with` or `query` entry with one of them is an error.

A request with `Accept: application/json` gets the view's data as JSON instead of the page.
## <a name="refusals"></a>When a capability refuses the page's data

| The capability | The answer |
| --- | --- |
| needs someone signed in, nobody is | a redirect to `/login` (`comeBack`: with `?return=`), with the authentication module; else `403` |
| refuses the person (`forbidden`) | `403` `[ERROR 1006] Forbidden` |
| finds nothing, or refuses the inputs | the `notFound` view with `404`, else `404` `[ERROR 1005] Page Not Found` |
## Reference

+ [`Route::page()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-page) and
  [`Route::pages()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-pages) (the pages declared so far,
  2.24.0: Snap shows a capability through the page made for it)
+ [`PageController::render()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Pages#pagecontroller-render): the
  controller every `Route::page` goes through
## Common mistakes

+ **A page whose data capability writes**: `Route::page` refuses it (opening a page must not change data). Use
  [`Route::form`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Form) for writes, or
  [`Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Action) when opening an address really has to
  change something.
+ **`/books/{id}` before `/books/new`**: `/books/new` shows the book `new` (a 404). Declare fixed addresses first.
+ **`signedIn` without `Auth::authentication(...)`** above the page: every visit stops with an error.
+ **Reading `$_GET` in the view**: only the names of `query` reach it. Add the name to `query`, or make it an input of
  the `data` capability.
+ **A `data` or `with` entry named `user` or `authorized`**: those names are reserved.

## Related pages

+ [Routing](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing): how a request finds its route, route variables
+ [Views](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views): Pug pages and the page components
+ [Forms: `Route::form`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Form)
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes): every route type in one page
+ [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries): what the `data` capabilities read with


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Route-Form -->

# Forms: `Route::form`

`Route::form($route, $capability, $options)` answers a form's `POST` (or its `PUT` or `DELETE` through `_method`) by
calling a capability with the form's fields, its files and the route variables (the route variables win), as the
person who sent it, then redirects. The page that shows the form stays a
[`Route::page`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Page). Since 2.19.0; `visitorsOnly`, `same`,
`accepted`, `inputs` and `signsIn` since 2.20.0, `signsInWith` since 2.21.7.

```php
Route::form('/books', 'create_book', ['success' => '/books/{id}', 'flash' => 'Book added']);
```
## With Claude

```text
/caligrafy-quill:new-capability create_book books:write
"Add a 'New book' form at /books/new for signed-in people. After saving, go to the book's page and say 'Book added'.
If a field is wrong, come back to the form with the message under the field and what was typed."
```

Claude writes the capability, the `Route::page` of the form and its `Route::form`, and the Pug view with `=csrf()`,
`old()`, `errors()` and `flash()`.

**Check** before you say OK:
+ the form has `method='POST'`, `=csrf()`, and `=methodField('PUT')` or `'DELETE'` for those routes;
+ `success` and `back` point at the pages that show `flash()` and `errors()`;
+ sending the form empty shows the messages under the fields, and the typed values stay.
## By hand

The `create_book` capability is the one of
[Declarative routes, step 1](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes).

1. **Declare the page and the form.** In `application/config/routing/web.php`:

   ```php
       Route::page('/books/new', 'Bookshelf/new', ['signedIn' => true, 'comeBack' => true, 'data' => ['authors' => 'list_authors']]);
       Route::form('/books', 'create_book', ['success' => '/books/{id}', 'flash' => 'Book added']);
       Route::form('/books/{id}', 'update_book', ['method' => 'PUT', 'success' => '/books/{id}', 'flash' => 'Saved']);
       Route::form('/books/{id}', 'delete_book', ['method' => 'DELETE', 'success' => '/books', 'flash' => 'Book deleted']);
   ```

2. **Write the form.** `application/views/Bookshelf/new.pug`:

   ```pug
   extends ../default/master/site

   block content
     section.cq-hero.cq-hero--page
       h1.cq-display New book

     section.cq-band.cq-band--tight
       .cq-inner.cq-inner--narrow
         if flash('error')
           .cq-alert.cq-alert--error(role='alert')= flash('error')
         form(method='POST', action=$home . 'books')
           =csrf()
           .cq-field
             label(for='title') Title
             input#title.form-control(type='text', name='title', value=old('title'))
             if errors('title')
               p.cq-field-error= errors('title')
           .cq-field
             label(for='author_id') Author
             select#author_id.form-select(name='author_id')
               each $a in $authors
                 option(value=$a['id'], selected=$a['id'] == old('author_id'))= $a['name']
             if errors('author_id')
               p.cq-field-error= errors('author_id')
           button.btn.btn-primary(type='submit') Add book
   ```

   A `PUT` or `DELETE` form adds `=methodField('PUT')` (or `'DELETE'`) after `=csrf()`.

3. **Try it.** On `/books/new`, send the form empty: the page comes back with "Some of the inputs are invalid" at the
   top and "The Title field is required" under the title. Fill it in: you land on `/books/<id>` with "Book added".
## <a name="outcomes"></a>What happens after the post

| The capability | The person goes to | The next page has |
|---|---|---|
| succeeds | `success`, its `{name}` filled from the result, then from the route variables; without `success`, back to the form | `flash('success')` with the `flash` message |
| refuses the input (`invalid`) or finds a duplicate (`conflict`) | back: the `back` option, else the page it came from (the `Referer`, when it is a page of this site), else `/` | `errors('title')`, `old('title')`, `flash('error')` |
| needs someone signed in, nobody is | the sign-in page (`signIn`, default `/login`); without the authentication module, `403` | |
| refuses the person (`forbidden`) | `403` `[ERROR 1006] Forbidden` | |
| finds nothing, or anything else | `404` `[ERROR 1005] Page Not Found` | |
## <a name="options"></a>Options

| Option | Default | What it does |
|---|---|---|
| `method` | `'POST'` | `'PUT'`, `'DELETE'`, or a list (`['POST', 'PUT']`); `GET` is refused (pages are `Route::page`) |
| `success` | back to the form | a path with `{placeholders}`, a full `https://` address, or `function ($result) { return '/books/' . $result['id']; }` |
| `flash` | none | the message for `flash('success')`, with `{placeholders}` as in `success`; or `['key' => 'message']` |
| `back` | the `Referer` of this site, else `/` | where invalid input goes, with the route's `{placeholders}`: `'back' => '/books/{id}'` |
| `error` | the capability's message | your message for `flash('error')`, or `['key' => 'message']` |
| `signIn` | `'/login'` | where a visitor goes when the capability needs someone |
| `visitorsOnly` | none | a path: people already signed in are sent there and the capability does not run; a JSON request gets `403` |
| `same` | none | fields that must match: `['password_again' => ['password', 'The two passwords are not the same']]`; without a message, "The two values are not the same" |
| `accepted` | none | boxes that must be ticked: `['terms' => 'Accept the terms of use']` |
| `inputs` | none | values only the server sets: an array, or `function ($input) { return [...]; }`. They replace what the form sent; the route variables still win |
| `signsIn` | none | the field of the capability's answer that holds the id of the person to sign in: `'signsIn' => 'id'`. A new session id and a new CSRF token, as for `Route::auth` |
| `signsInWith` | `'password'` | how `signsIn` signed the person in: what `AuthRoutes::signedInBy()` answers for that session (2.21.7) |

**The order of the checks.** `visitorsOnly`, then (JSON with the session) the CSRF header, then `same` and `accepted`,
then the capability. A form that breaks `same` or `accepted` never reaches the capability, and their messages arrive in
`errors('password_again')`, like the capability's. Both are read from what the person sent: declare `password_again` in
`$rules` only if the capability needs it.

**Values the form must not choose.** A form can send any field. `inputs` writes the ones only the server knows, over
anything the form sent: the address a payment page comes back to, the visitor's address, today's price.

**A form that leaves the site** for a payment page:

```php
Route::form('/orders/{order}/pay', 'start_checkout', [
    'inputs' => fn () => ['site' => session('home')],
    'success' => fn ($result) => $result['url'],
    'back' => '/orders',
]);
```

**A sign-up form that signs the person in**, for visitors only (`register_user` is the capability the authentication
module ships):

```php
Route::page('/join', 'Bookshelf/join', ['visitorsOnly' => '/books']);
Route::form('/join', 'register_user', [
    'visitorsOnly' => '/books',
    'same' => ['confirmpasscode' => ['passcode', 'The two passwords are not the same']],
    'accepted' => ['terms' => 'Accept the terms of use to create an account'],
    'signsIn' => 'id',
    'success' => '/books',
    'back' => '/join',
    'flash' => 'Welcome to the Bookshelf',
]);
```

`signsIn` is for a capability that creates or finds the person and answers their id: sign-up, an invitation link, a
confirmation code. A sign-in that decides how to sign in, or that has a state to check, is a
[`Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Action).
## <a name="helpers"></a>The view helpers

| Helper | What it gives |
|---|---|
| `=csrf()` | the hidden `_token` field every form post needs (`403` `[ERROR 3000]` without it) |
| `=methodField('PUT')` | the hidden `_method` field of a `PUT` or `DELETE` form |
| `errors()`, `errors('title')` | all the messages, or one field's (`null` when it has none) |
| `old('title', $default)` | what the person typed, else `$default` |
| `flash('success')`, `flash('error')` | the message of the last post; `flash('saved', 'Your changes are saved')` in your own code keeps one for the next request |

+ **One request only.** The errors, the old values and the messages are read by the next page, then gone.
+ Passwords, card numbers, tokens (any field whose name contains `pass`, `secret`, `token`, `card`, `cvc`, `cvv` or
  `iban`), files and `_` fields are never kept for `old()`.
+ **JSON**: a request with `Accept: application/json` gets the REST answer instead of redirects: `{"data": ...}` with
  `201` (a `POST` that changes data) or `200`, or `{"error": ...}` with `401`, `403`, `404`, `409` or `422`. With the
  session cookie it needs the `X-CSRF-Token` header.
## Reference

+ [`Route::form()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-form)
+ [`Caligrafy\Form`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#form): how the post is answered
+ [`Caligrafy\Flash`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#flash) and the helpers
  [`csrf()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-csrf),
  [`methodField()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-methodfield),
  [`errors()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-errors),
  [`old()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-old),
  [`flash()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-flash)
## Common mistakes

+ **`success` redirects to a page that redirects again**: the message is read by the page in between and lost. Point
  `success` and `back` at the page that shows it.
+ **A JSON post with the session and no `X-CSRF-Token`** answers `403`: send the header (`apiHeaders()` in the Vue
  apps).
+ **A placeholder with no value** (`'success' => '/authors/{author}'` when neither the result nor the route has
  `author`) stops with an error that names it.
+ **A file form without `enctype='multipart/form-data'`**: no file arrives
  ([File uploads](https://github.com/caligrafy/caligrafy-quill/wiki/File-Uploads)).
+ **`Route::form` on a `webOnly` capability**: it answers "There is no capability". Use `Route::action`.

## Related pages

+ [Pages: `Route::page`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Page)
+ [File uploads: the `file` rule](https://github.com/caligrafy/caligrafy-quill/wiki/File-Uploads)
+ [Validation](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation): the rules of `$rules`
+ [Views: forms](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#formhelpers)
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes): the complete Bookshelf example


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Route-Auth -->

# Sign-in pages: `Route::auth`

`Route::auth($options)` declares the sign-in, sign-out and sign-up pages in one line, with the views of the
authentication module, and no controller. It goes after `Auth::authentication('User', 'users');` in `web.php`. Since
2.19.0; `level` since 2.19.5, `attemptsPerUser` since 2.19.6, coming back after signing in since 2.20.0.

```php
Auth::authentication('User', 'users');
Route::auth(['home' => '/books']);
```

This page is about the declaration. Users, levels, tokens, password reset and the views are in
[Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication).
## With Claude

```text
"Add sign-in pages: after signing in, people land on /books."
```

**Check** before you say OK:
+ `Auth::authentication('User', 'users');` is above `Route::auth(...)` and the `users` table exists;
+ a page only signed-in people open says `'signedIn' => true` (and `'comeBack' => true` to land back on it);
+ no controller and no closure was written for the sign-in.
## By hand

1. **The `users` table.** Run:

   ```bash
   docker compose exec dev-box php caligrafer.php sql application/models/Auth/create_db.sql
   ```

2. **Turn on sign-in.** In `application/config/routing/web.php`, remove the `//` in front of
   `Auth::authentication('User', 'users');`, and add below it:

   ```php
       // sign-in pages: /login, /logout, /register, /notAuthorized
       Route::auth(['home' => '/books']);
   ```

3. **Try it.** Open `http://localhost:8080/register`, create an account (a username, a password typed twice), then
   sign in on `/login`: you land on `/books`.
## <a name="routes"></a>What it declares

| Route | What it does |
|---|---|
| `GET /login` | the sign-in page (`Auth/login`); a signed-in person goes to `home`, or to `?return=` |
| `POST /login` | checks the identifier field and `passcode`; on success a new session id and a new CSRF token, then `home`, or the page of `/login?return=` |
| `GET /logout`, `POST /logout` | signs out (a new session id and CSRF token), then `logout` |
| `GET /notAuthorized` | the page of people below the level a page needs (403) |
| `GET /register`, `POST /register` | the sign-up page (`Auth/register`) and the `register_user` capability, then `/login` |
| `POST /passkey/register/options`, `/passkey/register`, `/passkey/login/options`, `/passkey/login` | with `'passkeys' => true` only |
## <a name="options"></a>Options

| Option | Default | What it does |
|---|---|---|
| `home` | `'/'` | where people go after signing in (a signed-in person who opens `/login` goes there too) |
| `logout` | `'/'` | where people go after signing out |
| `register` | `true` | `true`: `/register` with the `register_user` capability; `false`: no sign-up; a capability name: yours |
| `identifier` | `'username'` | the `users` column people sign in with, and the name of the sign-in field (`'email'`) |
| `signInAfterRegister` | `false` | `true`: a new account is signed in and goes to `home` instead of the sign-in page |
| `attempts`, `lock` | `5`, `900` | failed sign-ins per username and address before a `429`, and the window in seconds |
| `attemptsPerUser` | `0` (off) | failed sign-ins of one username from any address before it is locked (2.19.6). Someone could lock a known username out on purpose: keep it high (20) |
| `level` | `0` | the lowest permission level that may sign in (2.19.5): below it, a sign-in is refused like a wrong password |
| `messages` | human words | what sign-in and sign-up say: `invalid`, `locked` (2.19.3, `{minutes}` is the wait), `mismatch`, `register_invalid`, `register_taken`, `registered` (2.19.4); the defaults are `AuthRoutes::MESSAGES` |
| `views` | `['login' => 'Auth/login', 'register' => 'Auth/register']` | your own views |
| `prefix` | `''` | `'/account'` gives `/account/login`... (the shipped views post to `/login`: write your own) |
| `passkeys` | `false` | `true` adds the passkey endpoints ([passkeys](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition#passkeys)) |

```php
// a users table with an email column: people sign in with it, and are signed in right after signing up
Route::auth(['home' => '/books', 'identifier' => 'email', 'signInAfterRegister' => true]);

// only administrators may sign in, in your own words
Route::auth(['home' => '/admin', 'level' => 1, 'messages' => ['invalid' => 'This account cannot sign in here.']]);
```
## <a name="behavior"></a>How it behaves

+ Signing in and signing out give the person a new session id and a new CSRF token.
+ The fifth failed sign-in for a username from one address within 15 minutes, and every one after it until the 15
  minutes end, answers `429` (2.19.3; `messages` sets your own words).
+ A JSON request with `X-CSRF-Token` gets `200` `{"data":{"user":{"id":1,"username":"ada","permissions":0}}}`, `401`
  or `429` in JSON: a Vue app signs in with the same routes.
+ Sign-up sends the register capability every input its `$rules` declare; nothing else of the form reaches it.
+ After signing in, a person goes to `home`, or to the page named by `/login?return=/books/3` (2.20.0). Only a path of
  this site is followed: another site, or `//evil.example`, is ignored. `Route::page` and `Route::action` with
  `'comeBack' => true` build that address for you.
+ `Route::auth` records how the session signed in, `password` or `passkey`, for `AuthRoutes::signedInBy()` (2.21.3).
+ **Not in `Route::auth`**: password reset and face sign-in. `'reset' => true` or `'face' => true` stops with an error.
  [Password reset](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#passwordreset) is `Route::page`
  and `Route::form`; [face sign-in](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition#face-login)
  is `Route::action`.
## Reference

+ [`Route::auth()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-auth)
+ [`Caligrafy\AuthRoutes`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AuthRoutes#authroutes):
  [`signIn()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AuthRoutes#authroutes-signin),
  [`signedInBy()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AuthRoutes#authroutes-signedinby),
  [`signOut()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AuthRoutes#authroutes-signout)
+ [`Caligrafy\Auth`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Auth#auth)
## Common mistakes

+ **`Route::auth` without `Auth::authentication('User', 'users')` above it**: there is no user model to sign in with.
+ **`'identifier' => 'email'` with the shipped `login.pug`**: the sign-in form posts a field named after the
  identifier, so the view needs an `email` field. For people who sign in with an email and no separate username, keep
  the address in `username` instead ([Signing in with an email](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#emailsignin)).
+ **A `prefix` with the shipped views**: they post to `/login`. Write your own views.
+ **`comeBack` with a `return=` you build by hand to another site**: it is ignored, the person goes to `home`.

## Related pages

+ [Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication): users, levels, tokens, password reset
+ [Pages: `Route::page`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Page): `signedIn`, `level`, `comeBack`, `visitorsOnly`
+ [Forms: `Route::form`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Form): a sign-up of your own with `signsIn`
+ [Face detection and face login](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Route-Webhook -->

# Webhooks: `Route::webhook`

A payment provider, a library service or GitHub posts events to an address of yours. `Route::webhook($route,
$capability, $options)` checks that the event comes from them (its signature), then calls a capability with it. There
is no session and no CSRF token: the signature is the only proof. Since 2.19.0.

```php
Route::webhook('/stripe/events', 'record_event', ['verify' => 'stripe']);   // STRIPE_WEBHOOK_SECRET=whsec_... in .env
```
## With Claude

```text
"Receive Stripe's checkout events at /stripe/events and record each one once."
```

**Check** before you say OK:
+ the route has `verify`, and the secret is the endpoint's `whsec_...`, not the API key;
+ the capability starts by refusing every caller that is not the webhook (`$context->actorType() !== 'webhook'`);
+ the same event posted twice is recorded once.
## By hand

1. **A table that remembers the events.** Run
   `docker compose exec dev-box php caligrafer.php migrate make create_webhook_events`, and write in the file it names:

   ```sql
   -- create_webhook_events
   CREATE TABLE IF NOT EXISTS webhook_events (
       id INT UNSIGNED NOT NULL AUTO_INCREMENT,
       event_id VARCHAR(100) NOT NULL,
       type VARCHAR(100) NOT NULL,
       created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
       PRIMARY KEY (id),
       UNIQUE KEY uq_webhook_events_event_id (event_id)
   ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
   ```

   Then `docker compose exec dev-box php caligrafer.php migrate`.

2. **The capability.** `docker compose exec dev-box php caligrafer.php service Bookshelf/RecordEvent`, then make
   `application/services/Bookshelf/RecordEvent.php` read:

   ```php
   <?php

   use Caligrafy\Capability;
   use Caligrafy\Context;
   use Caligrafy\Database;
   use Caligrafy\Service;
   use Caligrafy\ServiceError;

   #[Capability(
       name: 'record_event',
       description: 'Records an event that the library service posts (its id and type), once per event id.'
   )]
   class RecordEvent extends Service
   {
       public $rules = array('event' => 'required');

       public function handle(array $input, Context $context)
       {
           // only the webhook route may record events: REST, MCP and pages would let a signed-in user make one up
           if ($context->actorType() !== 'webhook') {
               throw ServiceError::forbidden('Only the library service sends events');
           }
           $event = $input['event'];
           if (!is_array($event) || empty($event['id']) || empty($event['type'])) {
               throw ServiceError::invalid(array('event' => 'The event needs an id and a type'));
           }
           // the sender posts an event again until it gets a 2xx: record each id once
           if (!Database::table('webhook_events')->where('event_id', $event['id'])->exists()) {
               Database::table('webhook_events')->insert(array('event_id' => $event['id'], 'type' => $event['type']));
           }
           return array('recorded' => $event['id']);
       }
   }
   ```

3. **The secret and the route.** Add the secret the sender gave you to `.env` (a placeholder here):
   `LIBRARY_WEBHOOK_SECRET=whsec_test_library`. In `web.php`, before `Route::run();`:

   ```php
       // the library service signs each event: X-Signature: sha256=<HMAC-SHA256 of the body with the secret>
       Route::webhook('/hooks/library', 'record_event', ['verify' => function ($rawBody, $headers) {
           $expected = 'sha256=' . hash_hmac('sha256', $rawBody, (string) getenv('LIBRARY_WEBHOOK_SECRET'));
           return hash_equals($expected, $headers['x-signature'] ?? '');
       }]);
   ```

4. **Post a signed event.** Run:

   ```bash
   BODY='{"id":"evt_1","type":"loan.returned"}'
   SIG="sha256=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac whsec_test_library -r | cut -d' ' -f1)"
   curl -s -i -X POST -H "Content-Type: application/json" -H "X-Signature: $SIG" http://localhost:8080/hooks/library -d "$BODY"
   ```

   It answers `200` with `{"received":true}`, and `webhook_events` has one row. The same post again adds nothing. With
   `-H "X-Signature: sha256=bad"`: `400` and `{"error":{"code":"invalid_signature","message":"The signature is not valid"}}`.
   A `GET` answers `405`.
## <a name="options"></a>Options

| Option | Default | What it does |
|---|---|---|
| `verify` | required | `'stripe'`, or `function (string $rawBody, array $headers): bool` (header names in lower case; only `true` passes) |
| `secret_env` | `'STRIPE_WEBHOOK_SECRET'` | with `'stripe'`: the `.env` variable that holds the endpoint's signing secret (`whsec_...`, not the API key) |
| `secret` | none | with `'stripe'`: the secret itself, instead of the variable (tests) |
| `tolerance` | `300` | with `'stripe'`: how many seconds old a signature may be |

`'stripe'` checks the `Stripe-Signature` header with the Stripe library. Anything else is a function of yours, as in
step 3.
## <a name="answers"></a>What the sender gets

| The event | The answer |
|---|---|
| signature checked, capability done | `200 {"received": true}` |
| bad or missing signature | `400 {"error":{"code":"invalid_signature",...}}` |
| a body that is not JSON | `400 {"error":{"code":"invalid","message":"The body is not JSON"}}` |
| the capability refuses (`ServiceError`) | its status and its error (`422` for `invalid`) |
| no secret set, no such capability, an error in the capability | `500`; the message goes to the PHP error log |

+ `verify` is required: a webhook without it stops with an error when `web.php` runs.
+ The body must be JSON; the capability gets `['event' => the decoded body]`, so declare `$rules = ['event' => 'required']`.
+ The capability runs as the system, with full access (`Context::system('webhook', $path)`; the audit log shows
  `webhook /hooks/library`): treat the event as data from outside. Before trusting an amount, ask the provider again
  ([Stripe](https://github.com/caligrafy/caligrafy-quill/wiki/9.2-Stripe-&-Cryptocurrency-Payment#webhook)).
+ Webhook addresses skip the CSRF check that every other form post goes through.
## Reference

+ [`Route::webhook()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-webhook)
+ [`Caligrafy\Webhook`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#webhook):
  [`verify()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#webhook-verify),
  [`process()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#webhook-process) (a test posts an event
  without a server)
+ [`Context::actorType()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#context-actortype)
## Common mistakes

+ **`'verify' => 'stripe'` without `STRIPE_WEBHOOK_SECRET`**: every event answers `500`. Use the endpoint's
  `whsec_...`, not the `sk_...` key.
+ **A webhook capability that is not idempotent**: services post an event again until they get a `2xx`, and a retried
  event is recorded twice.
+ **No `actorType()` check**: the capability is also served by REST, the JS client, MCP and `php caligrafer.php call`,
  to anyone its `scope` and `level` let in, with an event they made up.

## Related pages

+ [Stripe & cryptocurrency payment](https://github.com/caligrafy/caligrafy-quill/wiki/9.2-Stripe-&-Cryptocurrency-Payment#webhook)
+ [Migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations)
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#webhook)
+ [The audit log](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#audit)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Route-Download -->

# Downloads: `Route::download`

`Route::download($route, $capability, $options)` answers a `GET` with the result of a **read-only** capability as a
file: a CSV, a JSON file, or the files it lists in one ZIP. The capability stays plain data, so the same list also
reaches REST, the JS client and agents. Since 2.19.0; `columns` since 2.19.5, ZIP since 2.22.0.

```php
Route::download('/authors.csv', 'list_authors', ['filename' => 'authors.csv']);
Route::download('/books.json', 'list_books', ['as' => 'json']);   // a page of list_books, ?page=2 for the next
Route::download('/photos.zip', 'list_photo_files', ['as' => 'zip', 'root' => 'public/uploads/photos']);
```
## With Claude

```text
"Let people export the authors as CSV from a link on the authors page."
```

**Check** before you say OK:
+ the route names a read-only capability;
+ the export returns arrays with the columns it means to show (not models: they carry every property);
+ a ZIP's `root` is the folder that holds the files, relative to the project.

A step-by-step CSV export: [How to export a list as CSV](https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Export-a-List-as-CSV).
## <a name="options"></a>Options

| Option | Default | What it does |
|---|---|---|
| `as` | `'csv'` | `'csv'`, `'json'` (pretty-printed) or `'zip'` (the files the capability lists, 2.22.0); anything else stops with an error when `web.php` runs |
| `root` | `'public/uploads'` | for `zip`: the folder of the project the files are read from; a file outside it is never sent. A `root` with `..` stops with an error when `web.php` runs |
| `columns` | the first row's keys | the header row and its order, written even when there is no row: `['title', 'year']` (2.19.5) |
| `filename` | `<capability>.<as>` | a name, or `function ($result, $input) { return 'books-' . date('Y-m-d') . '.csv'; }` |
| `bom` | `false` | `true` starts the CSV with a UTF-8 BOM (Excel) |
| `formulas` | `false` | `true` keeps cells that start with `=`, `+`, `-`, `@` as they are |
| `signIn` | `'/login'` | where a visitor goes when the capability needs someone |
## <a name="inputs"></a>Inputs and refusals

+ The capability must be read-only: opening a link must not change data.
+ It gets the query string and the route variables (`/books.csv?author_id=2`) as the person who opens the link; the
  route variables win.
+ Refusals are those of `Route::page`: a visitor goes to sign in, `forbidden` is `403`, nothing found is `404`. An input
  to fix (`?author_id=abc`) answers `422` with the capability's error as JSON, as REST does (2.19.5; before, `404`).
+ The answer carries `Cache-Control: private, no-store` and `X-Content-Type-Options: nosniff`.
## <a name="csv"></a>CSV

+ The header row comes from `columns`, else from the first row's keys (then an empty result is an empty file).
+ Values are quoted where needed (RFC 4180, lines end with CRLF), UTF-8.
+ A text cell that starts with `=`, `+`, `-`, `@` or a tab gets a `'` first, so a spreadsheet does not run it as a
  formula (`formulas` turns that off).
+ Arrays in a cell are written as JSON, booleans as `true` / `false`. A related row (`with('author')`) is one cell, in
  JSON.
+ Each row of the list is a line. A `paginate()` page exports that page only: return `get()` to export every row; a
  single record gives one line.
+ **The columns are the keys of the first row.** A model carries every one of its properties:
  `Book::query()->select('id', 'title')->get()` exports `id`, `title` and every other column of `Book`, empty. Return
  arrays for a narrow export: `Database::table('books')->select('id', 'title')->get()` or
  `Book::query()->select('id', 'title')->arrays()->get()`.
## <a name="zip"></a>Many files as one ZIP (2.22.0)

The capability lists the files; `Route::download` puts them in one archive and sends it.

```php
#[Capability(name: 'list_photo_files', description: 'The files of the photos, oldest first', scope: 'photos:read', level: 1, readOnly: true)]
class ListPhotoFiles extends Service
{
    public function handle(array $input, Context $context)
    {
        return array_map(fn ($photo) => [
            'file' => $photo['image'],                                        // relative to 'root'
            'name' => 'pictures/' . date('Y-m-d_H-i-s', strtotime($photo['created_at'])) . '.jpg',   // in the archive
        ], Photo::query()->arrays()->select('image', 'created_at')->orderBy('created_at')->get());
    }
}
```

```php
Route::download('/photos.zip', 'list_photo_files', ['as' => 'zip', 'root' => 'public/uploads/photos',
    'filename' => fn ($files, $input) => 'photos-' . date('Y-m-d') . '.zip']);
```

+ **Each item** is a path (the file keeps its own name) or `['file' => path, 'name' => 'folder/name.jpg']`. Paths are
  relative to `root`; a `paginate()` page gives its rows.
+ **Only files under `root` go in.** A path that leaves it (`../../.env`), a folder, or a missing file is left out
  without an error. Names are cleaned (no `..`, no leading `/`), and a name used twice becomes `name (2).jpg`.
+ **No file at all answers `404`.** Hide the link when there is nothing to download, or throw
  `ServiceError::notFound('No photo yet')` in the capability.
+ Images, video, audio and archives are stored as they are; other files are compressed. The archive is written to a
  temporary file, sent with its `Content-Length`, then removed.
+ It needs PHP's **zip** extension: Caligrafy's Docker images and Caligrafy Cloud have it.
+ In a test, `Download::archive($files, ['root' => ...])` builds the same archive (`['path', 'count', 'names']`;
  remove `path` afterwards).
## Reference

+ [`Route::download()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-download)
+ [`Caligrafy\Download`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#download):
  [`archive()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#download-archive),
  [`csv()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#download-csv),
  [`rows()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#download-rows)
## Common mistakes

+ **A download of a capability that writes**: `Route::download` refuses it when the link is opened.
+ **A model query for a narrow export**: every column of the model is in the file. Return arrays.
+ **A ZIP whose files live outside `root`**: they are left out, and an empty list answers `404`. Give the folder that
  holds them, relative to the project (`public/uploads/photos`), and paths relative to it.
+ **A web-only capability that streams its own ZIP** (before 2.22.0): return the list and use `'as' => 'zip'`.

## Related pages

+ [How to export a list as CSV](https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Export-a-List-as-CSV)
+ [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries): `select()`, `arrays()`, `paginate()`
+ [Pages: `Route::page`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Page): the same refusals
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#download)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Route-Redirect -->

# Redirects: `Route::redirect`

`Route::redirect($from, $to, $status = 302, $options = [])` answers a `GET` by sending the visitor elsewhere, without
a closure or a controller: an address that moved, a short address, the home page of a section. Since 2.19.0;
`keepQuery` since 2.20.0.

```php
Route::redirect('/catalog', '/books');                   // 302
Route::redirect('/old/books/{id}', '/books/{id}', 301);  // moved for good
```
## With Claude

```text
"Redirect /catalog to /books, and the old /old/books/{id} addresses to /books/{id} for good."
```
## By hand

1. In `application/config/routing/web.php`, before `Route::run();`:

   ```php
       Route::redirect('/catalog', '/books');
   ```

2. Run `curl -s -i http://localhost:8080/catalog`: it answers `302 Found` with `Location: http://localhost:8080/books`.
## <a name="rules"></a>How it works

+ `{name}` in the target takes the route variable of the same name (url-encoded); the query string never fills it
  (`/old/books/2?x=1` goes to `/books/2`).
+ The target is a path of the site or a full `https://` address.
+ The status is `301`, `302` (default), `303`, `307` or `308`; anything else, or an empty target, stops with an error
  when `web.php` runs.
+ `['keepQuery' => true]` (2.20.0) takes the query string along: `/old?page=2` goes to `/new?page=2`. A `#fragment` of
  the target stays last.

```php
Route::redirect('/old', '/new', 301, ['keepQuery' => true]);
```
## Reference

+ [`Route::redirect()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-redirect),
  [`Route::withQuery()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-withquery),
  [`Route::redirectTarget()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-redirecttarget)
## Common mistakes

+ **A redirect that depends on who asks, or on the data**: that is a
  [`Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Action) whose capability returns
  `Web::redirect(...)`.
+ **`redirect()` in a closure without `return`**: `redirect()` only sends a `Location` header; code after it still
  runs. `Route::redirect` has no such problem.
+ **Expecting the query string to fill `{name}`**: only the route variables of `$from` do.

## Related pages

+ [Routing](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing): how a request finds its route
+ [Everything else: `Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Action)
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#redirect)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Route-Action -->

# Everything else: `Route::action` and web-only capabilities

`Route::page` shows a view and `Route::form` calls a capability and redirects. A few requests are neither: a sign-in
between two sites, a page that chooses between a view and a redirect, a gate, a page that creates a payment. Since
2.21.0 they are capabilities too, declared `webOnly: true` and served by one line, `Route::action($route, $capability,
$options)`. This is what replaces the controller of a new application.

```php
Route::action('/authors/{author_id}/books', 'open_author_books', ['back' => '/books']);
```
## With Claude

```text
"Add GET /authors/{author_id}/books: when the author has exactly one book, go straight to that book's page;
otherwise show the list."
```

**Check** before you say OK:
+ `webOnly: true` is on a capability that needs the session, signs someone in, or chooses between a page and a
  redirect; everything else stays a plain capability, so REST and agents can reach it;
+ the web-only capability calls the plain ones with `$this->capability()`;
+ no controller and no closure was written.
## By hand

1. **The capability.** Run `docker compose exec dev-box php caligrafer.php service Bookshelf/OpenAuthorBooks` and make
   `application/services/Bookshelf/OpenAuthorBooks.php` read:

   ```php
   <?php

   use Caligrafy\Capability;
   use Caligrafy\Context;
   use Caligrafy\Service;
   use Caligrafy\Web;

   // open_author_books: one book goes straight to its page, otherwise the list
   #[Capability(
       name: 'open_author_books',
       description: 'Opens the books of an author: the book itself when there is one, otherwise the list.',
       readOnly: true,
       public: true,
       webOnly: true
   )]
   class OpenAuthorBooks extends Service
   {
       public $rules = array('author_id' => 'required|integer');

       public function handle(array $input, Context $context)
       {
           $books = $this->capability('list_books', array('author_id' => $input['author_id']), $context);
           if ($books['total'] == 1) {
               return Web::redirect('/books/' . $books['data'][0]['id']);
           }
           return Web::view('Bookshelf/books', array('books' => $books));
       }
   }
   ```

2. **The route.** In `web.php`:

   ```php
       Route::action('/authors/{author_id}/books', 'open_author_books', ['back' => '/books']);
   ```

3. **Try it.**

   ```bash
   curl -s -i http://localhost:8080/authors/3/books | grep -iE "^HTTP|^Location"
   curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/authors/2/books
   curl -s -i http://localhost:8080/authors/abc/books | grep -iE "^HTTP|^Location"
   ```

   They print `302` to `/books/5` (one book), `200` (a list of two), and `302` to `/books` (the `back` option), where
   `flash('error')` says "Some of the inputs are invalid".
   `docker compose exec dev-box php caligrafer.php call open_author_books author_id=3` prints
   `{"error":{"code":"not_found","message":"There is no capability 'open_author_books'"}}`: only the route reaches it.
## <a name="options"></a>Options

```php
Route::action('/unlock/{name}', 'unlock_shelf', ['method' => 'POST']);
Route::action('/shelf/report', 'shelf_report', ['level' => 1, 'comeBack' => true]);
```

| Option | Default | What it does |
|---|---|---|
| `method` | `'GET'` | `'POST'`, `'PUT'`, `'DELETE'`, or a list (`['GET', 'POST']`) |
| `signedIn`, `level` | none | as in `Route::page`: visitors go to `/login`, people below the level to `/notAuthorized` |
| `comeBack` | `false` | with `signedIn` or `level`, or when the capability needs someone: visitors go to `/login?return=<this page>` |
| `visitorsOnly` | none | a path: people already signed in are sent there |
| `back` | the `Referer` of this site, else `/` | where invalid input or a conflict goes, with the route's `{placeholders}` |
| `error` | the capability's message | your message for `flash('error')` |
| `signIn` | `'/login'` | where a visitor goes when the capability needs someone (`comeBack` replaces it) |
## <a name="answers"></a>What it answers: `Caligrafy\Web`

| The capability returns | The browser gets |
|---|---|
| `Web::view('Bookshelf/book', $data, $status = 200)` | a Pug view, with `$authorized` and `$user` as on `Route::page` (`$data` wins). A request that asks for JSON gets the data as JSON |
| `Web::redirect('/books', $status = 302)` | a redirect: a path of this site or a full `http(s)` address |
| `Web::json($data, $status = 200)` | JSON, the data as it is, with no `{"data": ...}` around it |
| `Web::text($body, $status = 200)` | the text as it is |
| any of them `->header('Cache-Control', 'no-store')` | one more response header |
| plain data (an array, a model) | JSON, as with `Web::json` |

**When it refuses.** A capability that answers a refusal itself returns a `Web`. One that throws a `ServiceError` gets
the answers of `Route::form`:

| It throws | A browser | A JSON request |
|---|---|---|
| `invalid` or `conflict` | back (`back`, the `Referer`, or `/`) with `errors()`, `old()`, `flash('error')` | `422` or `409` and the REST error |
| `unauthenticated` | the sign-in page (`comeBack`: and back here) | `401` |
| `forbidden` | `403` `[ERROR 1006]` | `403` |
| `not_found` or anything else | `404` `[ERROR 1005]` | `404` |

**What it receives.** The inputs its `$rules` declare, from the form, the JSON body or the query string, and the route
variables, which win (`/books/3?id=9` gives `id = 3`, 2.21.2). Its files are saved and given as URLs, as for
`Route::form`. It runs as the person who sent the request, with its `public`, `scope` and `level` checks, its
validation and its audit log, like any capability.
## <a name="webonly"></a>What a web-only capability may do

**Only capabilities touch models**: a web-only capability is a capability. What sets it apart is what it may do besides:

| A plain capability | A web-only capability |
|---|---|
| returns data, or refuses | may also return a view, a redirect, JSON or text |
| never reads the session or the request: `$context` says who calls | may read `session()`, `request()`, `$_SERVER`, `$_COOKIE` |
| never signs anyone in | may sign people in and out |
| on a page, only `readOnly` | a `GET` may change data |
| reached by REST, MCP, the JS client, the command line, `Route::page`, `Route::form`, `$this->call()` | reached by **`Route::action` only** |

Everywhere else it answers `not_found` "There is no capability", and it is left out of `GET /capabilities`, MCP,
`php caligrafer.php capabilities` and `php caligrafer.php client`. So keep the work several channels share in plain
capabilities, and call them from the web-only one:

```php
$books = $this->capability('list_books', array('author_id' => 2), $context);   // as the same person, with its rules
```
## <a name="signin"></a>Signing someone in from an action

+ **A page that leaves or reloads**: `Caligrafy\AuthRoutes::signIn($user, null, 'partner')` gives a new session id, a
  new CSRF token, and records how the session signed in (the third argument, 2.21.3, read by
  `AuthRoutes::signedInBy()`).
+ **A page that stays open and keeps sending JSON**: `session_regenerate_id(true); Auth::authorize($user);
  AuthRoutes::rememberSignIn('face');`. The page keeps its token.
+ `$context` was built before the sign-in and does not change: to call a capability as the person just signed in,
  build a new one with `Context::fromRequest(request(), 'web')`.

A complete sign-in through another site is in
[Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#betweensites).
## <a name="csrf"></a>CSRF and JSON

+ A form's `POST`, `PUT` or `DELETE` needs its `_token` (`=csrf()`): `403` `[ERROR 3000]` without it.
+ A JSON call (`Accept: application/json`), `GET` included, needs the page's `X-CSRF-Token` header (`apiHeaders()` of
  the Vue apps) or, with `Auth::activateAPI();` in `web.php`, a token that grants everything (`--scopes "*"`), signed
  in or not: `401` `[ERROR 1004]` without it (2.21.1). A scoped token is refused: programs use the capability routes.
+ A plain `GET` opened by a link has no token, and can be triggered by a link on another site: keep a `GET` that
  changes data to what is harmless when that happens, and use `'method' => 'POST'` with a form for the rest.

**Tests.** `$this->action('open_author_books', ['author_id' => 3], $user)` calls it as `Route::action` does and returns
what it answered; `->describe()` gives `type`, `target`, `data`, `status` and `headers`. `$this->call()` answers
`not_found`, as every other channel does. See [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App#helpers).
## Reference

+ [`Route::action()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-action)
+ [`Caligrafy\Action`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#action) and
  [`Caligrafy\Web`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#web)
+ [`AuthRoutes::signIn()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AuthRoutes#authroutes-signin),
  [`AuthRoutes::rememberSignIn()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AuthRoutes#authroutes-remembersignin)
+ [`Context::fromRequest()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#context-fromrequest)
## Common mistakes

+ **`Route::action` on a capability without `webOnly: true`**, or `webOnly: true` behind `Route::page`, `Route::form` or
  REST: the first stops with an error that names it, the others answer "There is no capability".
+ **A web-only capability for work other channels need**: agents and programs cannot reach it. Put the work in a plain
  capability and call it with `$this->capability()`.
+ **A JSON call without `X-CSRF-Token`**: `401` `[ERROR 1004]`, even for a `GET` and for a visitor. Send `apiHeaders()`.
+ **`AuthRoutes::signIn()` on a page that stays open**: it gives the session a new CSRF token, and the page's next JSON
  call answers `401`. Use `session_regenerate_id(true); Auth::authorize($user);` there.
+ **Calling a capability as the person just signed in with the old `$context`**: it still says who called before. Build
  a new one with `Context::fromRequest(request(), 'web')`.

## Related pages

+ [How to move a controller route to a declared route](https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Move-a-Controller-Route-to-a-Declared-Route)
+ [Request](https://github.com/caligrafy/caligrafy-quill/wiki/3.-Request): what a web-only capability reads from the request
+ [Authentication: a sign-in through another site](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#betweensites)
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#action)
+ [Release notes 2.21.0](https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.21.0)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Route-Snap -->

# Snap Cards and the assistant: `Route::snap`

`Route::snap($options)` declares, in one line of `web.php`, every capability of the app as a card and an assistant that
answers with them. Since 2.23.0. This page is about the declaration; what people get, the card types, card views and
hints are in [Snap Cards and the assistant](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant).

```php
Auth::authentication('User', 'users');
Route::snap();
```
## With Claude

```text
"Add Snap Cards and the assistant to the app."
```

**Check** before you say OK:
+ `Route::snap();` is below `Auth::authentication(...)`;
+ `php caligrafer.php snap install` was run (the `caligrafy_snap_*` tables);
+ `/assistant` opens for a signed-in person and `/snap` lists the cards.
## By hand

1. **One line** in `application/config/routing/web.php`, after `Auth::authentication(...)`:

   ```php
   Route::snap();
   ```

2. **Its tables, and a starter hints file:**

   ```bash
   php caligrafer.php snap install
   ```

   It creates the `caligrafy_snap_*` tables (they also come with `php caligrafer.php platform install`, and with every
   deploy) and `application/config/snap.php`, then prints what is ready.

3. **Open `/assistant`.** The rest is optional: the `queue_work` job for background tasks, the `snap_routines_due` job
   for routines, and `ANTHROPIC_API_KEY` in `.env` for the assistant's model (without it, the assistant answers from the
   cards' names).
## <a name="routes"></a>What it declares

| Address | What it is |
|---|---|
| `GET /assistant` | Home (what needs you, insights, things to browse, shortcuts) and the task space; signed-in people only (`comeBack`) |
| `POST /assistant/ask` | what the person typed, said, attached or clicked (`snap_ask`, a `Route::action`) |
| `GET /assistant/noticed` | what the assistant noticed, and the person's routines (a settings page); signed-in people only |
| `GET /snap` | every card the person may use (a gallery); visitors see the public capabilities |
| `GET /snap/c/{capability}` | one card at its own address |
| `POST /snap/run` | a card sent (`snap_run`, a `Route::action`) |
| `POST /snap/call/{name}` | the `snap_*` capabilities the pages call, and only them, as the signed-in person |

Changes only ever run from a Confirm the person clicks.
## <a name="options"></a>Options

| Option | Default | What it does |
|---|---|---|
| `assistant` | `'/assistant'` | the path of the assistant and its pages |
| `cards` | `'/snap'` | the path of the cards and their routes |

```php
Route::snap(['assistant' => '/help', 'cards' => '/cards']);
```
## Reference

+ [`Route::snap()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-snap)
+ [Snap in the API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap):
  [`Snap\Cards`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Cards#snap-cards),
  [`Snap\Consent`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-consent),
  [`Snap\Setup`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-setup)
## Common mistakes

+ **"Snap is almost ready" (503)** on every Snap page: its `caligrafy_snap_*` tables are missing. Run
  `php caligrafer.php snap install` or `platform install` (after an `update` to 2.23.0, run one of them locally).
+ **`Route::snap()` without `Auth::authentication(...)` above it**: `/assistant` and `/assistant/noticed` are signed-in
  pages, and opening them stops with "'signedIn', 'level' and 'visitorsOnly' need Auth::authentication(...) in web.php".
+ **Expecting `async: true` to change REST or MCP**: `#[Capability(..., async: true)]` only changes Snap, where the
  card runs in the background as a Track: Task card.

## Related pages

+ [Snap Cards and the assistant](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant)
+ [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs)
+ [Scheduled jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs)
+ [Release notes 2.23.0](https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.23.0)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Route-Capability-and-REST -->

# Capability routes: REST, the JS client, MCP, notifications and bots

Five lines of `web.php` serve the capabilities to programs instead of browsers: one capability at one REST address
(`Route::capability`), all of them for the JS client (`Route::capabilities`), all of them as tools for AI agents
(`Route::mcp`), and two framework sets of routes, the pages of notification emails (`Route::notifications`) and the data
routes of the Watson bot apps (`Route::bots`).

```php
Route::capability('GET', '/api/books', 'list_books');          // one route, one capability, JSON
Route::capability('GET', '/api/books/{id}', 'get_book');       // {id} becomes the input "id"
Route::capability('POST', '/api/books', 'create_book');
Route::capabilities('/capabilities');                          // GET lists, POST /capabilities/{name} calls
Route::mcp('/mcp');                                            // AI agents: the capabilities their token allows
Route::notifications();                                        // the confirm and unsubscribe pages of notification emails
Route::bots();                                                 // the data routes of the Watson bot apps
```
## With Claude

```text
/caligrafy-quill:new-capability create_book books:write: also as POST /api/books, for the JS client, and for AI agents
```

**Check** before you say OK:
+ each REST route names a capability, never a closure;
+ `Route::mcp` is there when agents should use the app, and a token is created with only the scopes they need;
+ `php caligrafer.php client` was run again after adding or changing a capability.
## <a name="what"></a>What each one declares

| Line | Declares | Who calls |
|---|---|---|
| `Route::capability($method, $route, $name)` | `$method $route` (`GET`, `POST`, `PUT` or `DELETE`; anything else stops with an error) | programs with a personal access token, or a page of the app with the session |
| `Route::capabilities($prefix = '/capabilities')` | `GET {prefix}` (what the caller may call, with the input schemas and the session's CSRF token) and `POST {prefix}/{name}` | the JS client of the Vue apps and the SPA |
| `Route::mcp($route = '/mcp')` | `POST {route}` (one JSON-RPC message per request); `GET` and `DELETE` answer `405` | AI agents, with a personal access token only |
| `Route::notifications()` | `GET /notify/confirm/{token}`, `GET` and `POST /notify/unsubscribe` | the links of notification emails (2.15.0) |
| `Route::bots()` | `POST /__bots__/{appName}/communicate`, `POST /__bots__/{appName}/{appId}`, `DELETE /__bots__/{appName}` | the Watson bot apps of `public/` (2.21.0) |
## <a name="rest"></a>REST: `Route::capability`

```bash
curl -s http://localhost:8080/api/books/3
# {"data":{"id":3,"title":"Kindred","published_year":1979,...}}            200: get_book is public

curl -s -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" \
     -d '{"title": "X", "published_year": 1971, "author_id": 42}' http://localhost:8080/api/books
# {"error":{"code":"invalid","message":"Some of the inputs are invalid","fields":{"author_id":"There is no such author"}}}   422
```

+ **Requests**: a JSON body, form fields, or the query string for `GET`. Then the route variables, which win
  (`/books/3?id=9` gives `id = 3`, 2.21.2).
+ **Responses**: `200` with `{"data": ...}`, `201` when a `POST` changes data, or `{"error": {"code", "message",
  "fields"}}` with `401` (and `WWW-Authenticate: Bearer`), `403`, `404`, `409` or `422`.
+ **Who calls**: `Authorization: Bearer <token>`, or the session of a signed-in person. A session call that changes data
  needs the `X-CSRF-Token` header (`403` "Missing or invalid CSRF token" otherwise).
+ A `POST` with neither a token nor `Accept: application/json` is taken for a form and answers `403` `[ERROR 3000]`.
+ Files: a `file` rule takes the uploaded file ([File uploads](https://github.com/caligrafy/caligrafy-quill/wiki/File-Uploads)).
## <a name="client"></a>The JS client: `Route::capabilities`

```bash
docker compose exec dev-box php caligrafer.php client public/js/capabilities.js
```

writes one JavaScript function per capability, calling `/capabilities`. In a page of the app it uses the session (the
cookie, and the CSRF token it reads once from `GET /capabilities`); from Node or another site, a token:
`configure({ baseUrl: 'http://localhost:8080', token: process.env.CALIGRAFY_TOKEN })`.
`GET /capabilities` answers `{"data": [{"name", "description", "scope", "level", "readOnly", "destructive", "public",
"input"}, ...], "csrf": "<the session's CSRF token>"}`. More:
[The JS client](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#client).
## <a name="mcp"></a>AI agents: `Route::mcp`

Every capability the token allows is a tool, with its description, its input schema and the hints `readOnlyHint` and
`destructiveHint`. A refused call is a tool result with `"isError": true`, so the agent can correct itself.

```bash
claude mcp add --transport http bookshelf http://localhost:8080/mcp --header "Authorization: Bearer cq_..."
```

Without a token it answers `401` with `WWW-Authenticate` (2.19.1). MCP addresses skip the form CSRF check: the token is
the proof. More: [MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#mcp).
## Reference

+ [`Route::capability()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-capability),
  [`Route::capabilities()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-capabilities),
  [`Route::mcp()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-mcp),
  [`Route::notifications()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-notifications),
  [`Route::bots()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-bots)
+ [`Caligrafy\Rest`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#rest),
  [`Caligrafy\Client`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#client),
  [`Caligrafy\Mcp\Http`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#mcp-http),
  [`Caligrafy\Mcp\Server`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#mcp-server)
## Common mistakes

+ **A JSON write with the session and no `X-CSRF-Token`**: `403`. The JS client sends it; `fetch()` by hand must too.
+ **Data work in a closure route** (`Route::post('/x', function () {...})`): it has no permission rules and no CSRF
  check for JSON calls. Use `Route::capability`.
+ **MCP with the legacy API key**: refused (`401`); agents use personal access tokens.
+ **A `webOnly` capability behind these routes**: it answers "There is no capability"; only `Route::action` reaches it.
+ **A webhook's capability** is served by these routes too: guard it with `$context->actorType() !== 'webhook'`
  ([Webhooks](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Webhook)).

## Related pages

+ [Build once: services, capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP)
+ [Notifications](https://github.com/caligrafy/caligrafy-quill/wiki/Notifications)
+ [Creating bots with Watson](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.1-Creating-Bots-with-Watson)
+ [Vue: calling capabilities](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.3-Requests#capabilities)
+ [Routing](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing#capabilityroutes)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Export-a-List-as-CSV -->

# How to export a list as CSV

A link people click to download a list as a spreadsheet: one read-only capability that returns the rows, and one line
of `web.php`, `Route::download`. The same capability keeps serving the page, REST and agents. This guide exports the
authors of the Bookshelf, with a narrow set of columns and a dated file name.

Before you start: the Bookshelf tables of
[Routing, steps 1 to 3](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing#definingroutes). The commands run in
the project folder (with Docker: `docker compose exec dev-box php caligrafer.php ...`).
## With Claude

```text
/caligrafy-quill:new-capability export_authors books:read read-only public: the authors (id, name) sorted by name, downloadable as authors-<date>.csv from the authors page
```
## By hand

1. **The capability.** Run:

   ```bash
   docker compose exec dev-box php caligrafer.php service Bookshelf/ExportAuthors --scope books:read --read-only
   ```

   Make `application/services/Bookshelf/ExportAuthors.php` read:

   ```php
   <?php

   use Caligrafy\Capability;
   use Caligrafy\Context;
   use Caligrafy\Database;
   use Caligrafy\Service;

   #[Capability(
       name: 'export_authors',
       description: 'Lists the authors of the Bookshelf catalog, sorted by name: id and name.',
       scope: 'books:read',
       readOnly: true,
       public: true
   )]
   class ExportAuthors extends Service
   {
       public function handle(array $input, Context $context)
       {
           // arrays, not models: the columns of the file are the keys of the first row
           return Database::table('authors')->select('id', 'name')->orderBy('name')->get();
       }
   }
   ```

   It returns `get()`, every row; a `paginate()` page would export one page only.

2. **The route.** In `application/config/routing/web.php`, before `Route::run();`:

   ```php
       Route::download('/authors.csv', 'export_authors', [
           'columns' => ['id', 'name'],
           'filename' => fn ($rows, $input) => 'authors-' . date('Y-m-d') . '.csv',
           'bom' => true,
       ]);
   ```

   `columns` writes the header row even when there is no author yet; `bom` lets Excel read the accents.

3. **The link.** In the authors' page view:

   ```pug
   a.btn.btn-secondary(href=$home . 'authors.csv') Download as CSV
   ```

4. **Try it.** Run:

   ```bash
   curl -s -i http://localhost:8080/authors.csv
   ```

   It answers `200` with `Content-Type: text/csv; charset=utf-8`, `Content-Disposition: attachment;
   filename="authors-<today>.csv"`, the header row `id,name` and one line per author, lines ending with CRLF.
## Variations

+ **Filtered**: the query string and the route variables are the capability's inputs. A capability that declares
  `public $rules = array('author_id' => 'integer');` and filters on it is exported for one author with
  `/books.csv?author_id=2`; `?author_id=abc` answers `422` with the error as JSON.
+ **For signed-in people only**: drop `public: true`. A visitor who opens the link is sent to `/login` (`signIn` sets
  another page).
+ **JSON instead**: `'as' => 'json'`.
+ **The files themselves**: `'as' => 'zip'` ([Downloads, ZIP](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Download#zip)).
## Common mistakes

+ **A model query** (`Author::query()->select('id', 'name')->get()`): models carry every property, so every column of
  `Author` is in the file, empty. Return arrays (`Database::table(...)` or `->arrays()`).
+ **A capability that is not read-only**: `Route::download` refuses it.

## Related pages

+ [Downloads: `Route::download`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Download): every option
+ [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries)
+ [`Route::download()` in the API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-download)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers -->

# Controllers

A controller is a PHP class whose actions answer routes. It is how Caligrafy applications answered custom requests
before 2.21.0, and **a new application does not need one**: every request can be declared in one line of `web.php`
([Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes)), the rules of a feature live in a capability
(`application/services/`), and what a page or a form cannot say is a web-only capability served by `Route::action`.

Existing controllers keep working, with nothing to change. This page says what replaces each use of a controller, shows
how to move one, and documents the controllers you may still have.

## <a name="when"></a>What replaces a controller

| You need | Write | Where |
| --- | --- | --- |
| A page, with or without data | `Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book']]);` | [Routing](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing#pageroutes) |
| A page only signed-in people or administrators open | `Route::page(..., ['signedIn' => true])` or `['level' => 1]` | the same |
| A page that sends people back after signing in | `Route::page(..., ['signedIn' => true, 'comeBack' => true])` | the same |
| A page for visitors only | `Route::page('/join', 'Bookshelf/join', ['visitorsOnly' => '/books']);` | the same |
| A page that reads the query string | `Route::page(..., ['query' => ['sort' => 'title']])` | the same |
| A Vue, bot or machine learning app | `Route::page('/apps/{appName}', 'Client/app', ['query' => ['app' => 'index']]);` | [Routes for client apps](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.2-Routes) |
| A form that creates, changes or deletes | `Route::form('/books', 'create_book', ['success' => '/books/{id}']);` | [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form) |
| A sign-up with a confirmation field, a box to tick, that signs in | `Route::form` with `same`, `accepted`, `signsIn` | the same |
| A form that leaves for a payment page | `Route::form` with `'success' => fn ($r) => $r['url']` | [Payments](https://github.com/caligrafy/caligrafy-quill/wiki/9.2-Stripe-&-Cryptocurrency-Payment) |
| Password reset | `Route::page` and `Route::form` on two capabilities | [Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#passwordreset) |
| Sign-in, sign-out, sign-up | `Route::auth(['home' => '/books']);` | [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#auth) |
| Events Stripe or another service posts | `Route::webhook('/stripe/events', 'record_event', ['verify' => 'stripe']);` | [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#webhook) |
| A CSV or JSON file to download | `Route::download('/books.csv', 'list_books');` | [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#download) |
| An address that moved | `Route::redirect('/old/books/{id}', '/books/{id}', 301);` | [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#redirect) |
| A JSON API | `Route::capability('GET', '/api/books', 'list_books');` | [Routing](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing#capabilityroutes) |
| Several capabilities with conditions, a choice between a redirect and a view | `Route::action` and a web-only capability | [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#action) |
| The session, a sign-in of your own (face, another site), a gate, a payment page, custom headers | the same | [the same](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#webonly) |

`AdminController`, `AuthController`, `AIController`, `ClientController` and `WatsonController` ship in
`application/controllers/core/`, and the routes of a new project's `web.php` still name them. They are examples that work:
leave them, or replace their lines with the routes above.

## With Claude

```text
"Move application/controllers/BookController.php to declared routes."
"Add GET /authors/{author_id}/books: when the author has exactly one book, go straight to that book's page;
otherwise show the list."
```

For a new request, the `caligrafy` skill never writes a controller: Claude writes a capability in
`application/services/<Folder>/`, `webOnly: true` only when the request needs it, and one line of
`application/config/routing/web.php`. To move an existing controller, it writes one capability per action, swaps the
routes, removes the controller, and runs `php caligrafer.php test`. Ask the `caligrafy-reviewer` agent to review it: it
flags new controllers where a declared route fits.

**Check**

- [ ] `application/controllers/` got no new file.
- [ ] A capability with `webOnly: true` is one that returns a view or a redirect, reads the session, or signs someone
      in. The rest stays a plain capability, which REST and agents can reach.
- [ ] The web-only capability calls other capabilities with `$this->capability()`.
- [ ] `/authors/3/books` redirects and `/authors/2/books` shows the list.

## <a name="controllerstartup"></a>By hand: move a controller to a declared route

Before you start: the Bookshelf tables, the `Book` model, `list_books`, `get_book` and the views of
[Routing, steps 1 to 5](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing#definingroutes). You have this controller, and want it gone:

```php
<?php
// application/controllers/BookController.php

use Caligrafy\Controller;
use Caligrafy\ServiceError;

class BookController extends Controller
{
    // GET /authors/{author_id}/books: one book goes straight to its page, otherwise the list
    public function byAuthor()
    {
        try {
            $books = $this->call('list_books', array('author_id' => $this->request->fetch('author_id')));
        } catch (ServiceError $e) {
            http_response_code($e->status());
            return view('Bookshelf/notfound', array('message' => $e->getMessage()));
        }
        if ($books['total'] == 1) {
            redirect('/books/' . $books['data'][0]['id']);
            return null;
        }
        return view('Bookshelf/books', array('books' => $books));
    }
}
```

```php
Route::get('/authors/{author_id}/books', 'BookController@byAuthor');
```

1. <a name="createcontroller"></a>**Write the capability.** Run
   `docker compose exec dev-box php caligrafer.php service Bookshelf/OpenAuthorBooks`, and replace the content of
   `application/services/Bookshelf/OpenAuthorBooks.php` with:

   ```php
   <?php

   use Caligrafy\Capability;
   use Caligrafy\Context;
   use Caligrafy\Service;
   use Caligrafy\Web;

   // open_author_books: one book goes straight to its page, otherwise the list
   #[Capability(
       name: 'open_author_books',
       description: 'Opens the books of an author: the book itself when there is one, otherwise the list.',
       readOnly: true,
       public: true,
       webOnly: true
   )]
   class OpenAuthorBooks extends Service
   {
       public $rules = array('author_id' => 'required|integer');

       public function handle(array $input, Context $context)
       {
           $books = $this->capability('list_books', array('author_id' => $input['author_id']), $context);
           if ($books['total'] == 1) {
               return Web::redirect('/books/' . $books['data'][0]['id']);
           }
           return Web::view('Bookshelf/books', array('books' => $books));
       }
   }
   ```

   Each action becomes one capability. `$this->call()` becomes `$this->capability($name, $input, $context)`, `view()`
   `Web::view()`, `redirect()` `Web::redirect()`, `api()` `Web::json()`, and `$this->request->fetch('author_id')` an input
   declared in `$rules`.

2. <a name="controllerrouting"></a>**Swap the route.** In `application/config/routing/web.php`, replace the
   `Route::get` line with:

   ```php
       Route::action('/authors/{author_id}/books', 'open_author_books', ['back' => '/books']);
   ```

3. **Remove the controller.** Delete `application/controllers/BookController.php`.

4. **Try it.** Run:

   ```bash
   curl -s -i http://localhost:8080/authors/3/books | grep -iE "^HTTP|^Location"
   curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/authors/2/books
   curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/authors/9/books
   curl -s -i http://localhost:8080/authors/abc/books | grep -iE "^HTTP|^Location"
   ```

   They print `HTTP/1.1 302 Found` with `Location: http://localhost:8080/books/5` (Italo Calvino has one book, *Invisible
   Cities*), `200` (Octavia E. Butler's two books), `200` (the list with "No books yet.": nobody has the id 9) and
   `302` with `Location: http://localhost:8080/books` (`author_id` must be an integer: the `back` option, with the message
   in `flash('error')`).

   A JSON call needs the page's `X-CSRF-Token` header or a token that grants `*`, as on a controller route:

   ```bash
   curl -s -H "Accept: application/json" http://localhost:8080/authors/3/books
   ```

   prints `{"error":{"code":1004,"message":"Access Denied: send the page's CSRF token in an X-CSRF-Token header (pages,
   with the session cookie) or Authorization: Bearer <personal access token> (programs and agents)"}}` with `401`.

**Check**

- [ ] `/authors/3/books` redirects to `/books/5`, and `/authors/abc/books` to `/books`, not `500`.
- [ ] `php caligrafer.php call open_author_books author_id=3` answers `not_found`: only the route reaches it.
- [ ] `application/controllers/` no longer has the class, and `grep -n BookController application/config/routing/web.php`
      prints nothing.

**What moves, and what does not**

| In the controller | In the web-only capability |
| --- | --- |
| `$this->call('x', $input)` | `$this->capability('x', $input, $context)` |
| `$this->request->fetch('id')`, `$this->request->parameters()` | an input declared in `$rules` |
| `view('X', $data)`, with `'authorized' => authorized()` by hand | `Web::view('X', $data)`: `$authorized` and `$user` are given |
| `redirect('/x'); return;` | `return Web::redirect('/x');` |
| `http_response_code(422); return api($data);` | `return Web::json($data, 422);` |
| `header('X: y');` | `Web::text('...')->header('X', 'y')`, on any `Web` |
| `guard('permissions', 1);` | `'level' => 1` on the route, or `level: 1` on the capability |
| `try { ... } catch (ServiceError $e)` | nothing, unless you answer it yourself: `Route::action` sends it back like a form |
| `$_SESSION`, `authorized()`, `user()` | the same, a web-only capability may read them |
| a form and `=csrf()` | the same: a form's `POST` needs its token |
| a file: `uploadFile($this->request->files('x'))` | a `file` rule in `$rules`: `handle()` gets the URL |

## <a name="callcapability"></a>In a controller you keep: `$this->call()`

```php
$book = $this->call('create_book');                                  // inputs: the route variables and the request's fields
$books = $this->call('list_books', array('author_id' => 2));         // inputs you give
```

`$this->call($name, $input = null)` runs the capability as the person who sent the request (the signed-in user, a
token, or a visitor), with its validation, its permissions and its audit, exactly as REST and AI agents call it. It
returns plain data (arrays: `$book['id']`) or throws `Caligrafy\ServiceError`. It answers `not_found` for a capability
declared `webOnly: true`.

| `$e->kind` | `$e->status()` | When |
| --- | --- | --- |
| `invalid` | `422` | an input breaks a rule; `$e->fields` is `['title' => 'The Title field is required', ...]` |
| `unauthenticated` | `401` | the capability needs someone and nobody is signed in |
| `forbidden` | `403` | the person lacks the level, or the token the scope |
| `not_found` | `404` | the capability found nothing |
| `conflict` | `409` | a duplicate |

Without `$input`, the inputs are the route variables and the request's parameters (the form fields, the JSON body or,
for a `GET`, the query string); only the inputs the capability declares in `$rules` reach it. `$this->call()` does not
take uploaded files: a form with a file input posts to `Route::form`, `Route::action` or a capability route. The
framework's own user administration works this way: `AdminController` calls `list_users`, `get_user`, `update_user` and `delete_user`
([Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#usercapabilities)).

## <a name="namespacedcontrollers"></a>Namespaced controllers

A controller can live in a namespace. Declare it at the top of the file and use the full name in the route:

```php
<?php
// application/controllers/Shop/ReportController.php
namespace Shop;

use Caligrafy\Controller;

class ReportController extends Controller
{
    public function show()
    {
        header('Content-Type: text/plain; charset=utf-8');
        echo 'Report ' . $this->request->fetch('id');
    }
}
```

```php
Route::get('/reports/{id}', 'Shop\ReportController@show');
```

`curl -s -i http://localhost:8080/reports/7` answers `200` with `Content-Type: text/plain; charset=utf-8` and
`Report 7`.

How the router finds the class of `'Name@action'`:

1. a declared class named `Name` (global or fully qualified, with or without a leading `\`) is used: your own
   `AIController` wins over the example one;
2. otherwise, a short name (no backslash) falls back to the example controllers of `Caligrafy\Controllers`
   (`application/controllers/core/`: `AIController`, `AdminController`, `AuthController`, `ClientController`,
   `WatsonController`), so routes such as `'ClientController'` keep working;
3. otherwise the request answers `404` `[ERROR 1001] Invalid Controller or Action`, as for a missing action.

In a PHP single-quoted string `'Shop\ReportController'` and `'Shop\\ReportController'` are the same. The routes of a
new project use the full names (`'Caligrafy\\Controllers\\ClientController'`). Two classes with the same fully
qualified name in `application/` are an error.

## <a name="controllermethods"></a>Reference

A controller extends `Caligrafy\Controller`. Without an action in the route (`'BookController'`), `index()` runs; the
base `index()` does nothing. Do not give your own methods the names below.

| Property | What it is |
| --- | --- |
| `$this->request` | the [Request](https://github.com/caligrafy/caligrafy-quill/wiki/3.-Request) |
| `$this->validator` | a `Caligrafy\Validator` (GUMP with the framework's rules) |
| `$this->model` | the model set by `associate()` (an empty `Model` otherwise) |
| `$this->connection` | the database connection (PDO), or `null` |
| `$this->payment` | the Stripe module after `activatePayment()`, else `null` |
| `$this->loader` | `Caligrafy\Loader`: `library($name)`, `helper($name)` include a file of `framework/librairies` or `framework/helpers` |

| Method | What it does |
| --- | --- |
| `call($name, $input = null)` | runs a capability as the person who sent the request ([above](#callcapability)) |
| `view($viewName, $viewData = [])` | renders a Pug view; a request that asks for JSON gets `$viewData` as JSON |
| `api($viewData = [])` | answers `$viewData` as JSON |
| `check($data, $rules = [], $filters = [])`, `validate($data, $rules)`, `filter($data, $filters)` | GUMP validation and filtering ([Validation](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation#validationandfiltering)) |
| `activatePayment()` | sets `$this->payment` to a new `Caligrafy\Payment` |
| `associate($modelName, $table)`, `all()`, `find()`, `save()`, `delete()`, `search()`, `table()` | the classic model methods ([Other ways](#controllercontext)) |

`redirect('/path')` only sends a `Location` header: `return` right after it. Set a status with
`http_response_code($code)` before `view()` or `api()`.

## <a name="controllercontext"></a>Other ways: controllers that read and write models

Before capabilities, a controller read and wrote its model itself. These methods still work, for existing projects; a
new feature is a capability with `Route::form` or `Route::capability` instead, so the web, REST and agents follow the
same rules.

```php
<?php

use Caligrafy\Controller;

class LegacyBookController extends Controller
{
    public function show()
    {
        $this->associate('Book', 'books');   // the model class (or a Model object) and its table
        return api($this->find());           // the id comes from the {id} route variable
    }
}
```

| Method | What it does |
| --- | --- |
| `associate($modelName, $table)` | sets `$this->model`; call it again to work on another model in the same controller |
| `all($args = [])` | every row; `$args` adds `condition`, `order`, `limit` (raw SQL) and `bindings` |
| `find($id = null)` | one row; without `$id`, the `{id}` route variable |
| `save($inputs, $id = null)` | updates the row `$id` (or the `{id}` route variable), else creates one |
| `delete($id = null)` | deletes the row `$id` (or the `{id}` route variable) |
| `search($scope = null, $keywords = null)` | rows whose columns `$scope` (comma separated) match `$keywords` (bound; `%` and `_` are wildcards) |
| `table()` | the table of `$this->model` |

+ **`{id}` routes**: `find()`, `save()` and `delete()` take the `{id}` route variable when no id is given. On
  `POST /books/{id}/reviews`, `$this->save($review)` **updates** the review whose id is the book's id. Name the
  variable `{book_id}` or pass the id.
+ **`all($args)` clauses are SQL**: never put input in them; use `?` and `bindings`.
+ The replacement: a capability that uses the [query builder](https://github.com/caligrafy/caligrafy-quill/wiki/Queries),
  served with `Route::page`, `Route::form` and `Route::capability`.

## Common mistakes

+ **A new controller**: every request can be declared. A form post is `Route::form`, in one line, with `errors()`,
  `old()` and `flash()`; the rest is `Route::action`.
+ **Code after `redirect()`** keeps running: `return` after it.
+ **A JSON call from a page without `X-CSRF-Token`** answers `401` `[ERROR 1004]`: send `apiHeaders()` (Vue apps)
  or the token in the header.
+ **A scoped token on a controller route** is refused: controller routes, like `Route::action`, need a token that grants
  `*`. Give programs capability routes with scoped tokens instead.
+ **A short controller name that collides with an example controller** (`AuthController`): yours wins when it is
  declared; otherwise the example one answers.
+ **Overriding a base method** (`find`, `save`, `view`, `call`...) breaks the controller.

## Related pages

+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes): what replaces controllers
+ [Routing](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing#controllerroute): controller and closure routes
+ [Request](https://github.com/caligrafy/caligrafy-quill/wiki/3.-Request): `$this->request`
+ [Build once: services, capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#service)
+ [Validation](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation)

<br /><br />
>[Next Section: Learn about Helpers, Forms & REST API](https://github.com/caligrafy/caligrafy-quill/wiki/9.-Helpers-,-Forms-&-REST-API)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Move-a-Controller-Route-to-a-Declared-Route -->

# How to move a controller route to a declared route

Since 2.21.0 every request can be declared in one line of `web.php`, and a new application needs no controller.
Existing controllers keep working; this guide moves one action, `BookController@byAuthor`, to a web-only capability
served by `Route::action`, then removes the controller. The same steps move any action.

Before you start: the Bookshelf tables, the `Book` model, `list_books`, `get_book` and the views of
[Routing, steps 1 to 5](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing#definingroutes).
## With Claude

```text
"Move application/controllers/BookController.php to declared routes."
```

Claude writes one capability per action, swaps the routes, removes the controller, and runs `php caligrafer.php test`.
Ask the `caligrafy-reviewer` agent to review it: it flags controllers where a declared route fits.
## 1. Pick the route type

Most actions are not web-only. Choose the narrowest line that says what the action does:

| The action | Declare it with |
|---|---|
| shows a view, with data | [`Route::page`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Page) and read-only capabilities |
| saves a form, then redirects | [`Route::form`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Form) |
| sign-in, sign-out, sign-up | [`Route::auth`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Auth) |
| receives another service's events | [`Route::webhook`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Webhook) |
| sends a file | [`Route::download`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Download) |
| always sends to the same address | [`Route::redirect`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Redirect) |
| answers JSON to programs | [`Route::capability`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Capability-and-REST) |
| chooses between a view and a redirect, reads the session, signs someone in | [`Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Action) |

The action below chooses between a redirect and a view: a `Route::action`.
## 2. The controller you have

```php
<?php
// application/controllers/BookController.php

use Caligrafy\Controller;
use Caligrafy\ServiceError;

class BookController extends Controller
{
    // GET /authors/{author_id}/books: one book goes straight to its page, otherwise the list
    public function byAuthor()
    {
        try {
            $books = $this->call('list_books', array('author_id' => $this->request->fetch('author_id')));
        } catch (ServiceError $e) {
            http_response_code($e->status());
            return view('Bookshelf/notfound', array('message' => $e->getMessage()));
        }
        if ($books['total'] == 1) {
            redirect('/books/' . $books['data'][0]['id']);
            return null;
        }
        return view('Bookshelf/books', array('books' => $books));
    }
}
```

```php
Route::get('/authors/{author_id}/books', 'BookController@byAuthor');
```
## 3. Write the capability

Run `docker compose exec dev-box php caligrafer.php service Bookshelf/OpenAuthorBooks`, and make
`application/services/Bookshelf/OpenAuthorBooks.php` read:

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;
use Caligrafy\Web;

// open_author_books: one book goes straight to its page, otherwise the list
#[Capability(
    name: 'open_author_books',
    description: 'Opens the books of an author: the book itself when there is one, otherwise the list.',
    readOnly: true,
    public: true,
    webOnly: true
)]
class OpenAuthorBooks extends Service
{
    public $rules = array('author_id' => 'required|integer');

    public function handle(array $input, Context $context)
    {
        $books = $this->capability('list_books', array('author_id' => $input['author_id']), $context);
        if ($books['total'] == 1) {
            return Web::redirect('/books/' . $books['data'][0]['id']);
        }
        return Web::view('Bookshelf/books', array('books' => $books));
    }
}
```

**What moves, and how:**

| In the controller | In the web-only capability |
| --- | --- |
| `$this->call('x', $input)` | `$this->capability('x', $input, $context)` |
| `$this->request->fetch('id')`, `$this->request->parameters()` | an input declared in `$rules` |
| `view('X', $data)`, with `'authorized' => authorized()` by hand | `Web::view('X', $data)`: `$authorized` and `$user` are given |
| `redirect('/x'); return;` | `return Web::redirect('/x');` |
| `http_response_code(422); return api($data);` | `return Web::json($data, 422);` |
| `header('X: y');` | `Web::text('...')->header('X', 'y')`, on any `Web` |
| `guard('permissions', 1);` | `'level' => 1` on the route, or `level: 1` on the capability |
| `try { ... } catch (ServiceError $e)` | nothing, unless you answer it yourself: `Route::action` sends it back like a form |
| `$_SESSION`, `authorized()`, `user()` | the same, a web-only capability may read them |
| a form and `=csrf()` | the same: a form's `POST` needs its token |
| a file: `uploadFile($this->request->files('x'))` | a `file` rule in `$rules`: `handle()` gets the URL |
## 4. Swap the route

In `application/config/routing/web.php`, replace the `Route::get` line with:

```php
    Route::action('/authors/{author_id}/books', 'open_author_books', ['back' => '/books']);
```
## 5. Remove the controller and try it

Delete `application/controllers/BookController.php`, then run:

```bash
curl -s -i http://localhost:8080/authors/3/books | grep -iE "^HTTP|^Location"
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/authors/2/books
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/authors/9/books
curl -s -i http://localhost:8080/authors/abc/books | grep -iE "^HTTP|^Location"
```

They print `302` with `Location: http://localhost:8080/books/5` (one book), `200` (two books), `200` (the list with
"No books yet.": nobody has the id 9) and `302` to `/books` (`author_id` must be an integer: the `back` option, with
the message in `flash('error')`).

**Check**

- [ ] `/authors/3/books` redirects to `/books/5`, and `/authors/abc/books` to `/books`, not `500`.
- [ ] `php caligrafer.php call open_author_books author_id=3` answers `not_found`: only the route reaches it.
- [ ] `grep -n BookController application/config/routing/web.php` prints nothing.
- [ ] `php caligrafer.php test` passes; a test of the action uses `$this->action(...)`, not `$this->call(...)`.
## Common mistakes

+ **Everything made web-only**: a web-only capability is reached by `Route::action` only. Work that REST, the JS client
  or agents also need stays a plain capability, called with `$this->capability()`.
+ **A JSON call without `X-CSRF-Token`**: `401` `[ERROR 1004]`, as on the controller route it replaces.
+ **Moving the examples that ship in `application/controllers/core/`** (`AdminController`, `AuthController`,
  `AIController`, `ClientController`, `WatsonController`): they work; leave them, or replace their lines with
  `Route::auth`, `Route::page('/apps/{appName}', 'Client/app', ['query' => ['app' => 'index']])` and `Route::bots()`.

## Related pages

+ [Controllers](https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers): the controllers you may still have
+ [Everything else: `Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Route-Action)
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#controller)
+ [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App#helpers)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.-Helpers-%2C-Forms-%26-REST-API -->

# Helpers, forms and REST API

Three things that every Caligrafy app uses: the **global helpers** (functions such as `view()`, `redirect()`,
`csrf()`, `old()`), **forms** (a form posts to a capability with `Route::form`, protected by a CSRF token), and the
**REST API** (each capability as a JSON endpoint with `Route::capability`, called with a personal access token). The
same capability answers the form, the API, the Vue apps and AI agents.

## With Claude

```text
/caligrafy-quill:new-capability create_book books:write
"Give create_book a REST endpoint at POST /api/books, and a token for my import script."
```

Claude writes the capability, the `Route::capability` line in `application/config/routing/web.php`, and creates the
token with `php caligrafer.php token create "<what it is for>" --scopes books:write`. The token is shown once: store it
as a secret yourself; Claude never writes it into a file of the project. For a form, the same skill writes
`Route::form` and the view ([Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form)).

**Check**

- [ ] `curl` with the token answers `201` and `{"data": ...}`; without it, `401`.
- [ ] A token without the scope answers `403` "This needs the scope books:write".
- [ ] A missing input answers `422` with `fields`.
- [ ] No token, key or secret was written to a file of the project or printed in a commit.

## By hand: a REST API

Before you start: the Bookshelf tables, `list_books` and `get_book` of
[Routing, steps 1 to 3](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing#definingroutes), and `create_book`
of [Declarative routes, step 1](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form). The
framework tables must be installed (`docker compose exec dev-box php caligrafer.php platform install`, done by the
Quickstart).

1. **Declare the endpoints.** In `application/config/routing/web.php`, before `Route::run();`:

   ```php
       // the Bookshelf REST API: one route, one capability
       Route::capability('GET', '/api/books', 'list_books');
       Route::capability('GET', '/api/books/{id}', 'get_book');
       Route::capability('POST', '/api/books', 'create_book');
   ```

2. **Create a token for the program that calls it.** Run:

   ```bash
   docker compose exec dev-box php caligrafer.php token create "Bookshelf script" --scopes "books:read,books:write"
   ```

   It prints ` Token #<n> "Bookshelf script" created with books:read books:write`, the token (`cq_<id>_<40 hex
   characters>`) and ` It is shown only now: store it as a secret (Authorization: Bearer <token>).`

3. **Call the API.** Run:

   ```bash
   curl -s -H "Accept: application/json" http://localhost:8080/api/books/3
   ```

   It prints `{"data":{"id":3,"title":"Kindred","published_year":1979,"summary":"A young woman is pulled back in time to a plantation in Maryland.","author_id":2,"created_at":"...","modified_at":"...","author":{"id":2,"name":"Octavia E. Butler",...}}}`
   (`get_book` is public: no token needed). Create a book with the token:

   ```bash
   curl -s -i -X POST -H "Accept: application/json" -H "Authorization: Bearer cq_..." \
        -H "Content-Type: application/json" http://localhost:8080/api/books \
        -d '{"title":"The Dispossessed","published_year":1974,"author_id":1}'
   ```

   It answers `201` with `{"data":{"id":<new id>,"title":"The Dispossessed","published_year":1974,...,"author":{"id":1,"name":"Ursula K. Le Guin",...}}}`.
   The same call without the `Authorization` header answers `401` with
   `{"error":{"code":"unauthenticated","message":"Sign in or send a personal access token"}}`; with
   `-d '{"title":"","published_year":1969,"author_id":9}'` it answers `422` with
   `{"error":{"code":"invalid","message":"Some of the inputs are invalid","fields":{"title":"The Title field is required","author_id":"There is no such author"}}}`.

**Check**

- [ ] `GET /api/books` answers `{"data":{"data":[...],"total":6,"page":1,"per_page":20,"pages":1}}` (a page of
      `list_books`).
- [ ] `POST /api/books` with the token answers `201`; without it `401`; with a `books:read` token `403`.
- [ ] `docker compose exec dev-box php caligrafer.php audit --capability create_book` lists the call.

## <a name="restapi"></a>REST API

A capability becomes a JSON endpoint in one line. The route variables become inputs (`{id}` is the input `id`).

```php
Route::capability('GET', '/api/books', 'list_books');
Route::capability('GET', '/api/books/{id}', 'get_book');
Route::capability('POST', '/api/books', 'create_book');
Route::capability('PUT', '/api/books/{id}', 'update_book');
Route::capability('DELETE', '/api/books/{id}', 'delete_book');
Route::capabilities('/capabilities');   // GET /capabilities lists what the caller may call; POST /capabilities/{name} calls one
```

**Who may call.** A personal access token (`Authorization: Bearer cq_...`) that grants the capability's scope
(`books:write`, `books:*` or `*`), or the signed-in person (a page of the app, with the session cookie). A session call
that changes data also sends the CSRF token in an `X-CSRF-Token` header (`GET /capabilities` returns it in `csrf`; the
Vue apps send it with `apiHeaders()`). A `public: true` capability answers anyone. Tokens:
`php caligrafer.php token create <name> --scopes <scopes> [--user <id>] [--expires <days>]`, `token list`,
`token revoke <id>` ([Personal access tokens](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#tokens)).

**Inputs.** The JSON body (or the form fields, or the query string for a `GET`), and the route variables, which win
(2.21.2: `/api/books/3?id=9` is the book 3).
Only the inputs the capability declares in `$rules` reach it. A `file` input takes a multipart upload
(`curl -F "cover=@cover.png"`) ([File inputs](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#files)).

**Answers.**

| Status | Body | When |
| --- | --- | --- |
| `200` | `{"data": ...}` | the capability answered |
| `201` | `{"data": ...}` | a `POST` to a capability that changes data |
| `401` | `{"error":{"code":"unauthenticated",...}}` (with `WWW-Authenticate: Bearer`) | nobody signed in and no valid token |
| `403` | `{"error":{"code":"forbidden","message":"This needs the scope books:write"}}` | the token lacks the scope, the person the level, or a session write lacks `X-CSRF-Token` |
| `404` | `{"error":{"code":"not_found",...}}` | the capability found nothing |
| `409` | `{"error":{"code":"conflict",...}}` | a duplicate |
| `422` | `{"error":{"code":"invalid","message":"...","fields":{"title":"..."}}}` | an input breaks a rule |

**Errors of the framework** (not of a capability) answer with a real status too, and JSON to a JSON request:

| Status | Error | When |
| - | - | - |
| `401` | `1004` Access Denied | a JSON call to `Route::action` or a controller route, `GET` included, without `X-CSRF-Token` (pages) or a token that grants `*`. The message ends with the reason |
| `403` | `3000` Cross Site Forgery | a form post without a valid `_token` |
| `403` | `1006` Forbidden | a `Route::page`, `Route::form`, `Route::action` or `Route::download` whose capability refuses the person |
| `404` | `1001` Invalid Controller or Action | a route names a controller or an action that does not exist |
| `404` | `1005` Page Not Found | no route matches, or a page's capability finds nothing |
| `405` | `1000` Invalid Http Request Method | the address exists with other methods (`Allow` header) |
| `500` | any other error | the message is shown only with `APP_DEBUG=true` for PHP fatal errors |

```json
{"error":{"code":1005,"message":"Page Not Found"}}
```

Test with `curl` or an API client (Postman, Bruno): set `Accept: application/json`, `Content-Type: application/json`
for a JSON body, and the `Authorization: Bearer cq_...` header.

### Other ways: controller APIs and the legacy API key

Before capabilities, an API was a controller whose actions returned `api($data)`:

```php
Route::get('/legacy/books/{id}', 'LegacyBookController@show');   // the controller of 8.-Controllers, Other ways
```

+ A JSON call to a controller route needs, with `Auth::activateAPI();` in `web.php` (the template has it), a token
  that grants **everything** (`--scopes "*"`), or the page's `X-CSRF-Token` header. Scoped tokens are refused there:
  give programs capability routes instead.
+ **The legacy API key** (`php caligrafer.php generatekeys`, `generateapikey`) is the `APP_KEY` encrypted with itself:
  every key of one `APP_KEY` is valid, and they cannot be revoked one by one. It still works while `LEGACY_API_KEY` is
  not `false` (Caligrafy Cloud sets `false`). Give each program a personal access token instead.
+ `api($data)` and `view(null, $data)` print `$data` as JSON; set a status first with `http_response_code()`. The
  replacement is a capability with `Route::capability`: the same rules for the web, REST and agents.

## <a name="forms"></a>Forms

A form posts to `Route::form`, which calls a capability and redirects
([Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form) has the complete
example):

```php
Route::page('/books/new', 'Bookshelf/new', ['signedIn' => true, 'data' => ['authors' => 'list_authors']]);
Route::form('/books', 'create_book', ['success' => '/books/{id}', 'flash' => 'Book added']);
Route::form('/books/{id}', 'update_book', ['method' => 'PUT', 'success' => '/books/{id}', 'flash' => 'Saved']);
```

```pug
form(method='POST', action=$home . 'books')
  =csrf()
  .cq-field
    label(for='title') Title
    input#title.form-control(type='text', name='title', value=old('title'))
    if errors('title')
      p.cq-field-error= errors('title')
  button.btn.btn-primary(type='submit') Add book
```

| In the view | What it gives |
| --- | --- |
| `=csrf()` | `<input type='hidden' name='_token' value='<the session's CSRF token>'>`: every `POST`, `PUT` and `DELETE` form needs it |
| `=methodField('PUT')` | `<input type='hidden' name='_method' value='PUT'>`: the form reaches a `PUT` (or `DELETE`) route |
| `errors('title')` | the message of the field after a refused post, or `null`; `errors()` gives them all |
| `old('title', $default)` | what the field held after a refused post, else `$default` (never passwords or other secrets) |
| `flash('success')`, `flash('error')` | the message of the previous post; `flash('key', 'text')` keeps one for the next request |

**CSRF** (cross-site request forgery: another site making your visitor's browser post to your app). The framework
checks every `POST`, `PUT` and `DELETE` that is not JSON: its `_token` must be the session's token, else `403`
`[ERROR 3000] Security Error - Cross Site Forgery`. A script that sends JSON sends the token in an `X-CSRF-Token`
header instead. Read the token with `session('token')`, never `$_SESSION['token']`: since 2.19.0 a session starts
only when it is needed.

A form that does more than call one capability and redirect posts to a
[`Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#action) (`'method' => 'POST'`): same `=csrf()`, same `errors()`, `old()` and `flash()` after a
refusal, and the capability chooses what comes next. In plain HTML the field is
`<input type="hidden" name="_token" value="<?= session('token') ?>">`.

### Other ways: a hand-written form to a controller

A form in older code posts to a controller route (`Route::post('/books', 'BookController@store')`) whose action calls
`$this->call('create_book')` and renders the errors itself. It keeps working
([Controllers](https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers#callcapability)), and it needs `=csrf()` too.

## <a name="helpers"></a>Helpers

Global functions of `framework/helpers/corehelpers.php`, available everywhere in `application/` and in the views.

**Views, requests and routing**

| Function | What it does |
| --- | --- |
| `view($viewName, $viewData = [])` | renders `application/views/<viewName>.pug` with the data; a request that asks for JSON gets the data as JSON |
| `api($viewData = [])` | answers the data as JSON |
| `redirect($url)` | sends a `Location` header: a path of the site, or a full `http(s)://` address as it is. It does not stop the script: `return` after it |
| `request()` | a new `Caligrafy\Request` |
| `currentRoute()`, `currentBind()` | the matched route pattern and its variables |
| `csrf()`, `methodField($method)` | print the hidden `_token` and `_method` inputs (`=csrf()` in Pug) |
| `errors($field = null)`, `old($field, $default = '')`, `flash($key, $value = null)` | the form helpers ([above](#forms)) |
| `connect()` | the database connection (PDO) |
| `import($filename)` | includes `framework/librairies/<name>.php` or `framework/helpers/<name>.php` |

**Session and page settings**

| Function | What it does |
| --- | --- |
| `session($key, $value = null)` | reads a session value, or saves one (any value but `null`, including `0`, `''` and `false`) |
| `saveInSession($data, $name)`, `clearFromSession($name)` | save or remove a session value |
| `scripts($key, $value = null)` | the URL of a front-end library (`bootstrap_css`, `bootstrap_script`, `vue`, `axios`, `jquery`, `wysiwyg_css`, `wysiwyg_js`...), pinned in `framework/settings/coresettings.php`; override one in `application/config/config.php` with `scripts('vue', '<url>')` |
| `metadata($pairs = [])` | merges `title`, `description`, `image`... into the page's metadata and returns it ([Metadata](https://github.com/caligrafy/caligrafy-quill/wiki/9.3-Metadata-&-Social-Rich-Cards)) |
| `keywords($value = null)`, `copyright($value = null)` | the page keywords and the copyright line |
| `design_stylesheet()` | the URL of the `DESIGN_STYLE` stylesheet, or `''` |
| `terminateSession($url)` | empties the session and redirects |
| `getGlobalInformation($superGlobal = 'session')` | `$_SESSION`, or `'post'`, `'get'`, `'files'` (those are then unset) |
| `isSessionExpired($time)` | whether the session was idle more than `$time` seconds |

**Files**

| Function | What it does |
| --- | --- |
| `uploadFile($file, $allowedExtensions = null)` | moves a `$_FILES` entry to `public/uploads/<random>.<ext>` and returns its public URL, or `''` when refused. In a capability, the `file` rule does this for you |
| `isAllowedUpload($filename, $allowedExtensions = null)` | whether `uploadFile()` would accept the name. Default list `DEFAULT_UPLOAD_EXTENSIONS`: jpg jpeg png gif webp bmp ico heic pdf txt csv md rtf doc docx xls xlsx ppt pptx odt ods odp mp3 wav ogg m4a mp4 mov webm avi zip json. Scripts and markup (php, phtml, phar, cgi, pl, py, sh, asp, jsp, htaccess, ini, svg, html, js, exe, bat) are always refused |
| `deleteFile($url)` | deletes a file of `public/uploads/` by its URL (never a hidden file) |
| `imageCanva()` | a new `claviska\SimpleImage` for image changes ([SimpleImage](https://github.com/claviska/SimpleImage)) |
| `rearrange($files)` | turns a multiple file input's `$_FILES` entry into one array per file |

**HTTP and mail**

| Function | What it does |
| --- | --- |
| `httpRequest($url, $method, $data, $headers, $username = null, $password = null)` | a cURL request; `$data` is sent as JSON for every method but `GET`; returns the decoded JSON |
| `httpFile($url, $filepath, $headers, $username = null, $password = null, $purpose = 'assistants')` | posts a file (multipart) |
| `sendMail($recipients, $emailContent, $from)` | sends an email through `MAIL_HOST`, `MAIL_PORT`, `MAIL_USERNAME`, `MAIL_PASSWORD`: `['email' => ..., 'name' => ...]`, `['subject' => ..., 'body' => '<p>html</p>']`, `['email' => ..., 'name' => ...]`; returns `true` or `false` |

**Authentication** (need `Auth::authentication('User', 'users');` in `web.php`)

| Function | What it does |
| --- | --- |
| `authorize($user)`, `unauthorize()` | signs a user in or out of the session (`Route::auth` does this for you) |
| `authorized()` | whether someone signed in is still valid |
| `user()` | the signed-in user |
| `guard($attribute, $level, $loginUrl = '/login', $notAuthorized = '/notAuthorized')` | sends visitors to `$loginUrl` and people below `$level` to `$notAuthorized`, then stops |
| `logout($redirectUrl = '/')` | signs out, ends the session and redirects |

**Strings, arrays, time and keys**

| Function | What it does |
| --- | --- |
| `generateToken($size = 12)` | `2 × $size` random hexadecimal characters |
| `generateKey($size = 32)` | random bytes in base64 (the `APP_KEY` format) |
| `encryptDecrypt($action, $data, $key = APP_KEY)` | `'encrypt'` or `'decrypt'` with AES-256-CBC |
| `sanitize($string)` | `htmlentities()` in UTF-8 |
| `isJson($string)` | whether the string is valid JSON |
| `findKey($array, $key)`, `recursive_filter(&$array, $allowed)` | find a key at any depth; keep only allowed keys |
| `arraySort($array, $attribute, $sort = SORT_DESC)` | sorts rows by a column |
| `loadConstantFromArray($array)` | defines a constant for each key |
| `parsePath($path)`, `sanitizePath($path)`, `startWith($s, $p)`, `endWith($s, $p)` | path and string checks |
| `bindRouteToVar($route, $uri)`, `parseRoute($path)` | the variables of a route pattern |
| `singularize($word)` | drops the last letter (`books` -> `book`, but `categories` -> `categorie`) |
| `now()` | the current time as `Y-m-d H:i:s` |
| `getRelativeTime($datetime, $depth = 1)` | `3 days ago`, `2 hours left` |

## Common mistakes

+ **A form without `=csrf()`** answers `403` `[ERROR 3000]`.
+ **`fetch()` from the browser without `Accept: application/json`**: it is treated as a form post and needs `_token`.
+ **A JSON session call that writes, without `X-CSRF-Token`**: `403` "Missing or invalid CSRF token".
+ **A scoped token on a controller route**: `401` `[ERROR 1004]`; controller routes need `*`.
+ **Code after `redirect()`** keeps running.
+ **`$_SESSION['token']` read before the session started** is empty: use `session('token')`.
+ **Checking the status of a client call as `200` only**: errors answer with their real status (since the security
  release; earlier versions answered `200`).

## Related pages

+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes): `Route::form` and the file rule
+ [Views: forms](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#formhelpers)
+ [Build once: REST, tokens, the JS client, MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#rest)
+ [Vue apps: requests](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.3-Requests): `apiHeaders()`
+ [Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication)

<br /><br />
>[Next Section: Learn about Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.7.0-Setting-up-Vue.js-as-a-library -->

**Vue as a library** is the shortest way to add a Vue screen to a Caligrafy application: no Node.js, no build step. Vue 3 loads from a pinned CDN address, your markup is a `.php` file in `public/<app>/`, your script is `public/<app>/scripts/main.js`, and Caligrafy serves the page through a page route. The app reads and writes data by calling your capabilities through the generated JS client. For a larger app with its own routes and a build, see the [Vite single page app](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.1---Setting-up-the-Vue-application).
## With Claude

```text
/caligrafy-quill:new-app app bookshelf
```
Then describe the screen: "a list of the books with an add form, through the books capabilities". Claude checks the name, runs `php caligrafer.php app bookshelf`, generates `public/js/capabilities.js`, adds the page route to `application/config/routing/web.php`, and writes `public/bookshelf/index.php` and `public/bookshelf/scripts/main.js` with the page components.

**Check** before you say OK:
+ The address Claude gives opens the screen, and the browser console has no error.
+ `main.js` loads `public/js/capabilities.js` and calls the capabilities by name; no `apiKey`, no `Authorization` header.
+ Adding a book without a year shows `The Published Year field is required` under the year.
## By hand

You build the Bookshelf screen at `/bookshelf`: the books, 20 a page, and a form to add one. You need the Bookshelf tables and capabilities (`list_books`, `create_book`, `list_authors`) of [Views, steps 1 to 3](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#viewsstartup), and `Route::capabilities('/capabilities');` in `application/config/routing/web.php` (the Quickstart adds it). Commands run in the project folder with the Docker server; addresses start with `http://localhost:8080/`.

**1. Scaffold the app.** Run:
```bash
docker compose exec dev-box php caligrafer.php app bookshelf
```
Expected: `Project created in the public folder.` It copies `framework/plugins/app` to `public/bookshelf/`: `index.php` and `scripts/main.js`. The name must not be a folder Caligrafy already uses in `public/` (`app`, `bot`, `__bots__`, `css`, `facedetect`, `fonts`, `images`, `js`, `ml`, `resources`, `uploads`) and `public/bookshelf/` must not exist yet.

**2. Generate the JS client.** Run:
```bash
docker compose exec dev-box php caligrafer.php client public/js/capabilities.js
```
Expected: `public/js/capabilities.js written: <n> capabilities, calls /capabilities (Route::capabilities('/capabilities') in web.php)`. Run it again after every change to a capability.

**3. The page route.** In `application/config/routing/web.php`, above `Route::run();`, write:
```php
    // BOOKSHELF: the Vue app (public/bookshelf/index.php)
    Route::page('/bookshelf', 'Client/app', ['with' => ['appName' => 'bookshelf', 'app' => 'index']]);
```
Open `http://localhost:8080/bookshelf`: the template's screen, *My Vue app*, lists the capabilities a visitor may call (`create_book`, `get_book`, `list_books`...).

**4. The markup.** Replace `public/bookshelf/index.php` with:
```php
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
        <title>Bookshelf</title>
        <link rel="shortcut icon" href="<?php echo scripts('favicon'); ?>" type="image/x-icon" />
        <link rel="stylesheet" href="<?php echo scripts('bootstrap_css'); ?>" />
        <link rel="stylesheet" href="<?php echo session('public').'css/theme.css';?>">
        <link rel="stylesheet" href="<?php echo session('public').'css/tokens.css';?>">
        <link rel="stylesheet" href="<?php echo session('public').'css/layout.css';?>">
        <link rel="stylesheet" href="<?php echo session('public').'css/look.css';?>">
        <?php if (design_stylesheet()): ?><link rel="stylesheet" href="<?php echo design_stylesheet(); ?>"><?php endif; ?>
    </head>

    <body class="cq-site">
        <div id="app" v-cloak>
            <nav class="cq-nav" aria-label="Main">
                <a class="cq-nav-brand" :href="env.home"><img class="cq-nav-mark" :src="env.home + 'public/images/resources/caligrafy-mark.svg'" alt="" width="28" height="28"><span class="semibold">Book</span>shelf</a>
            </nav>
            <section class="cq-hero cq-hero--page">
                <h1 class="cq-display">Books</h1>
                <p class="cq-lead">{{ total }} books on the shelf.</p>
            </section>
            <section class="cq-band cq-band--tight">
                <div class="cq-inner cq-inner--narrow">
                    <p class="cq-alert cq-alert--error" role="alert" v-if="error">{{ error }}</p>
                    <form method="POST" novalidate @submit.prevent="addBook">
                        <div class="cq-form-grid cq-form-grid--2">
                            <div class="cq-field">
                                <label for="title">Title</label>
                                <input id="title" class="form-control" type="text" maxlength="200" v-model="book.title">
                                <p class="cq-field-error" v-if="errors.title">{{ errors.title }}</p>
                            </div>
                            <div class="cq-field">
                                <label for="author_id">Author</label>
                                <select id="author_id" class="form-select" v-model.number="book.author_id">
                                    <option v-for="author in authors" :key="author.id" :value="author.id">{{ author.name }}</option>
                                </select>
                                <p class="cq-field-error" v-if="errors.author_id">{{ errors.author_id }}</p>
                            </div>
                            <div class="cq-field">
                                <label for="published_year">Year</label>
                                <input id="published_year" class="form-control" type="number" v-model.number="book.published_year">
                                <p class="cq-field-error" v-if="errors.published_year">{{ errors.published_year }}</p>
                            </div>
                            <div class="cq-field">
                                <label for="summary">Summary</label>
                                <input id="summary" class="form-control" type="text" maxlength="2000" v-model="book.summary">
                            </div>
                        </div>
                        <button class="btn btn-primary" type="submit">Add book</button>
                    </form>
                    <ul class="cq-rows" v-if="books.length">
                        <li class="cq-row" v-for="item in books" :key="item.id">
                            <div class="cq-row-main">
                                <p class="cq-row-title">{{ item.title }}</p>
                                <p class="cq-row-meta">{{ item.author.name }}, {{ item.published_year }}</p>
                            </div>
                        </li>
                    </ul>
                    <p class="cq-empty-state" v-else>No books yet: add the first one above.</p>
                    <p v-if="pages > 1">
                        <button class="btn btn-secondary" type="button" :disabled="page === 1" @click="load(page - 1)">Previous</button>
                        <button class="btn btn-secondary" type="button" :disabled="page === pages" @click="load(page + 1)">Next</button>
                    </p>
                </div>
            </section>
        </div>

        <script src="<?php echo scripts('vue'); ?>"></script>
        <script src="<?php echo APP_SERVICE_ROOT.'app.js?v='.@filemtime(PUBLIC_PATH.'js/services/app.js'); ?>"></script>
        <script>loadEnvironment(`<?php echo $env; ?>`);</script>
        <script>loadVue({ scripts: ['main'] });</script>
    </body>
</html>
```

**5. The script.** Replace `public/bookshelf/scripts/main.js` with:
```js
// Bookshelf: the books of the catalog, through the generated JS client (public/js/capabilities.js)
const app = Vue.createApp({
    data () {
        return {
            env: env,
            books: [], total: 0, page: 1, pages: 1,
            authors: [],
            book: { title: '', author_id: null, published_year: null, summary: '' },
            errors: {},
            error: ''
        }
    },
    async mounted () {
        this.api = await import(env.home + 'public/js/capabilities.js')
        this.api.configure({ baseUrl: env.home.replace(/\/$/, '') })   // the application root, whatever APP_ROOT is
        this.authors = await this.api.listAuthors()
        await this.load(1)
    },
    methods: {
        async load (page) {
            const result = await this.api.listBooks({ page: page })   // { data, total, page, per_page, pages }
            this.books = result.data
            this.total = result.total
            this.page = result.page
            this.pages = result.pages
        },
        async addBook () {
            this.errors = {}
            this.error = ''
            try {
                await this.api.createBook(this.book)
                this.book = { title: '', author_id: null, published_year: null, summary: '' }
                await this.load(1)
            } catch (e) {
                if (e.name === 'CapabilityError' && e.code === 'invalid') this.errors = e.fields
                else this.error = e.message
            }
        }
    }
})

app.mount('#app')
```

**6. Try it.** Reload `http://localhost:8080/bookshelf`:
+ The title band says `5 books on the shelf.`, the list shows them sorted by title (`Ursula K. Le Guin, 1968` under *A Wizard of Earthsea*), and the Author list holds the three authors.
+ Type `Dawn`, choose Octavia E. Butler, leave the year empty, press **Add book**: `The Published Year field is required` appears under the year, and the title stays.
+ Type `1987` and press **Add book**: the count says `6 books on the shelf.`, *Dawn* is in the list, and the fields are empty.

**Check**
+ The browser console shows no error other than the `422` of the refused book, and the network panel shows `POST /capabilities/list_authors`, `list_books` and `create_book`, each with an `X-CSRF-Token` header.
+ The page source contains no API key in `main.js` and no `Authorization` header is sent.
+ At phone width the two fields stack and the rows stay readable.
## Reference

| What | Value |
| --- | --- |
| Command | `php caligrafer.php app <name>` (or `.bin/caligrafer app <name>`): copies `framework/plugins/app` to `public/<name>/` |
| Files | `public/<name>/index.php` (the markup: a `.php` file, so it can use Caligrafy's helpers), `public/<name>/scripts/main.js` (loaded by `loadVue({ scripts: ['main'] })`) |
| Script versions | `app.js?v=<file time>` in the markup (2.21.6), and `loadVue()` adds `?v=<env.scripts_version>` to `scripts/<name>.js` (2.21.5): each deploy reaches every browser |
| Vue | `scripts('vue')`: Vue 3.5.45, the global production build from jsDelivr, pinned in `framework/settings/coresettings.php` |
| Page route | `Route::page('<path>', 'Client/app', ['with' => ['appName' => '<name>', 'app' => 'index']])`, or the ready-made `/apps/<name>` ([Routes](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.2-Routes)) |
| JS client | `php caligrafer.php client public/js/capabilities.js`; loaded with `await import(env.home + 'public/js/capabilities.js')` because `main.js` is a classic script ([Requests](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.3-Requests#capabilities)) |
| Stylesheets | `theme.css`, `tokens.css`, `layout.css`, `look.css` and the design style, as in the template; `body.cq-site` and the page components |

`configure({ baseUrl })` matters when the application is not at the root of its address (`APP_ROOT` not empty, for example `http://localhost:8888/myapp/` with MAMP): without it the client calls `/capabilities` at the root of the server.
## Other ways

+ **The template's own screen.** Before step 4, the template lists the capabilities the visitor may call (`await this.api.capabilities()`): use it to see what a visitor or a signed-in user may do.
+ **Copying the template yourself.** Without PHP on the computer, `cp -r framework/plugins/app public/bookshelf` is what the command does.
## Common mistakes

+ **Running `app <name>` for a folder that exists**: the template is copied inside it, as `public/<name>/app/`. Pick a new name.
+ **`import` at the top of `main.js`**: it is a classic script; load the client with `await import(...)` inside `mounted()`.
+ **The client file is missing**: the template's screen says `The JS client is missing`, and your own script stops with a failed import in the console. Run step 2.
+ **A capability added later is not in the client**: run step 2 again.
+ **`Bearer ' + apiKey` in old scripts**: the legacy key is public and turned off on Caligrafy Cloud (`LEGACY_API_KEY=false`): call the capabilities through the client.
## Related pages

+ [The flow of information](https://github.com/caligrafy/caligrafy-quill/wiki/9.7-Understanding-the-flow-of-information)
+ [Views: page components](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#pagecomponents)
+ [Build once: the JS client](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#client)
> [Next Section: Understanding the flow of information](https://github.com/caligrafy/caligrafy-quill/wiki/9.7-Understanding-the-flow-of-information)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.7.3-Requests -->

A Vue app asks the server for data, and sends it what people type, through **requests**. In Caligrafy the app does not build these requests: `php caligrafer.php client` writes a JavaScript module with one function per capability (`listBooks()`, `createBook()`), and each function sends the request with the visitor's session and CSRF token, then returns the answer or throws a `CapabilityError`. This page is the reference of that client.
## With Claude

Ask for the screen and the data it needs: "the bookshelf app lists the books 20 at a time with Previous and Next". Claude uses the generated client (`/caligrafy-quill:new-app`, `/caligrafy-quill:new-capability`) and runs `php caligrafer.php client` again when a capability changes.

**Check** before you say OK:
+ Every call goes through a function of `capabilities.js`; no `axios`, `fetch` or `Authorization` header written by hand for capabilities.
+ A refused call is caught: `invalid` shows the field messages, any other error shows its message.
+ `public/js/capabilities.js` was generated again after the last capability change (its functions match `php caligrafer.php capabilities`).
## <a name="capabilities"></a>By hand: calling capabilities

You call the Bookshelf capabilities from the Bookshelf app of [Setting up Vue as a library](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.0-Setting-up-Vue.js-as-a-library), then from a Node script.

**1. Generate the client.** `web.php` needs `Route::capabilities('/capabilities');`. Run:
```bash
docker compose exec dev-box php caligrafer.php client public/js/capabilities.js
```
Expected: `public/js/capabilities.js written: <n> capabilities, calls /capabilities (Route::capabilities('/capabilities') in web.php)` and an example line `import { createBook, CapabilityError } from './capabilities.js'`.

**2. Load it in the app.** In `public/bookshelf/scripts/main.js`, `mounted()` loads it and points it at the application:
```js
this.api = await import(env.home + 'public/js/capabilities.js')
this.api.configure({ baseUrl: env.home.replace(/\/$/, '') })
```

**3. Call it.** Open `http://localhost:8080/bookshelf`, then type in the browser console:
```js
const api = await import(env.home + 'public/js/capabilities.js')
await api.listBooks({ page: 1 })
```
Expected: `{data: Array(n), total: n, page: 1, per_page: 20, pages: 1}`, the paged answer of `list_books`. Then:
```js
await api.getBook({ id: 3 })
```
Expected: `{id: 3, title: 'Kindred', published_year: 1979, ..., author: {id: 2, name: 'Octavia E. Butler', ...}}`.

**4. A refusal.** Type:
```js
try { await api.createBook({ title: 'Lilith' }) } catch (e) { console.log(e.name, e.status, e.code, e.fields) }
```
Expected: `CapabilityError 422 invalid {published_year: 'The Published Year field is required', author_id: 'The Author Id field is required'}`.

**5. From a Node script.** Programs use a personal access token instead of a session. Run:
```bash
docker compose exec dev-box php caligrafer.php token create "bookshelf script" --scopes books:read,books:write
```
It prints the token once (`cq_...`). Copy `public/js/capabilities.js` next to your script as `capabilities.mjs`, and write `books.mjs`:
```js
import { configure, listBooks, createBook, CapabilityError } from './capabilities.mjs'

configure({ baseUrl: 'http://localhost:8080', token: process.env.CALIGRAFY_TOKEN })
const page = await listBooks({ page: 1 })
console.log(page.total, page.pages)
try {
  await createBook({ title: 'Lilith' })
} catch (e) {
  console.log(e instanceof CapabilityError, e.status, e.code, JSON.stringify(e.fields))
}
```
Run `CALIGRAFY_TOKEN=cq_... node books.mjs` (Node.js 18 or later). Expected: the number of books and of pages (`5 1` with the sample data), then `true 422 invalid {"published_year":"The Published Year field is required","author_id":"The Author Id field is required"}`.

**Check**
+ In the browser's network panel, writes carry `X-CSRF-Token` and no `Authorization`; the first write is preceded by one `GET /capabilities`.
+ The Node script sends `Authorization: Bearer cq_...` and no cookie.
## Reference

### The generated module

`php caligrafer.php client [<file>] [--prefix /capabilities]` writes an ES module with no dependency (default file `public/js/capabilities.js`). Run it again after adding or changing a capability.

| Export | What it does |
| --- | --- |
| `listBooks(input = {})`, `createBook(input)`... | one function per capability: `create_book` becomes `createBook`. A JSDoc comment gives its description, whether it reads, writes or destroys, who may call it, and its inputs |
| `call(name, input = {})` | calls a capability by name: `call('create_book', {...})` |
| `capabilities()` | the capabilities this caller may use, with their input schema |
| `configure(options)` | `baseUrl` (default `''`: this origin), `token` (a personal access token), `prefix` (default the `--prefix`, `/capabilities`), `credentials` (default `'same-origin'`) |
| `CapabilityError` | thrown on a refusal: `status` (HTTP), `code`, `message`, `fields` (`{}` unless `invalid`) |

Each function sends `POST <baseUrl><prefix>/<name>` with the input as JSON and `Accept: application/json`, and returns what is inside `data`. With a `token` it sends `Authorization: Bearer <token>`; without one, writes send `X-CSRF-Token`, read once from `GET <baseUrl><prefix>` (the answer's `csrf`), and the browser sends the session cookie.

### Answers

| Capability returns | The function returns |
| --- | --- |
| a row (`Book::find()`, `->first()`) | an object: `{id, title, published_year, ...}` |
| a list (`->get()`) | an array of objects |
| a page (`->paginate(20)`) | `{data, total, page, per_page, pages}`; with `with('author')` each book has its `author` object |

### Refusals

| `code` | `status` | When |
| --- | --- | --- |
| `invalid` | 422 | an input breaks a rule of `$rules`: `fields` has one message per field |
| `unauthenticated` | 401 | the capability is not public and nobody is signed in (no token) |
| `forbidden` | 403 | the caller lacks the scope or level, or a write of a signed-in session came without `X-CSRF-Token` (a visitor's write to a `public` capability needs no token) |
| `not_found` | 404 | no capability with that name, or the capability answered `not_found` |
| `conflict` | 409 | the capability refused a duplicate or a state change |
| `error` | other | no JSON error in the answer (a server error) |

### Where the app runs

| App | Client | `baseUrl` |
| --- | --- | --- |
| Vue as a library | `public/js/capabilities.js`, loaded with `await import(env.home + 'public/js/capabilities.js')` | `env.home` without its last `/` |
| Vite single page app | `public/<app>/src/capabilities.js`, `import { listBooks } from '@/capabilities.js'` | `''` (same origin; in development the Vite proxy forwards `/capabilities`) |
| A Node script or another site | a copy of the module | the application's address, with a `token` |
## Other ways: `Route::action` and controller routes with `fetch` or axios

The generated client reaches capabilities. A JSON route of your own, a [`Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#action) or a controller route in older code, is called with `fetch` or axios. What other experiences need belongs in a capability: the same rules then serve pages, REST and agents.

+ **The headers.** A JSON call from a page to its own `Route::action` (`GET` included, signed in or not, 2.21.1) or controller route sends `Accept: application/json` and the session's token in `X-CSRF-Token` (since 2.7.0): `apiHeaders()` of `public/js/services/app.js` returns both. The controller then sees the signed-in person or a visitor, as for a form post. Without them the route answers `401` and `{"error":{"code":1004,"message":"Access Denied: send the page's CSRF token in an X-CSRF-Token header (pages, with the session cookie) or Authorization: Bearer <personal access token> (programs and agents)"}}`.
  ```js
  const response = await fetch(env.home + 'api/shelf', { headers: apiHeaders() })
  const books = await response.json()
  ```
  For a JSON body with `fetch`, add the type: `apiHeaders({ 'Content-Type': 'application/json' })`. axios is not in the template: add `<script src="<?php echo scripts('axios'); ?>"></script>` (axios 1.21.1) before `app.js`, then `axios.get(env.home + 'api/shelf', { headers: apiHeaders() })`; axios sets `Content-Type` itself (JSON for an object, multipart for a `FormData`) and rejects an error status (`error.response.status`, `error.response.data`).
+ **Form requests.** A request without `Accept: application/json` is a form request: its `POST`, `PUT` and `DELETE` carry the CSRF token as the form field `_token` (`formData.append('_token', env.token)`), otherwise `403` (`[ERROR 3000]`). PHP does not read form data sent with a real `PUT`: send `POST` with `_method` set to `PUT` ([Forms](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.4-Forms)).
+ **The legacy API key** (`'Bearer ' + apiKey`): readable by anyone who opens the page, and turned off on Caligrafy Cloud (`LEGACY_API_KEY=false`, then `env.apiKey` is `null`). Do not use it.
## Common mistakes

+ **`/capabilities` not found under a sub-folder** (`APP_ROOT` not empty): call `configure({ baseUrl: env.home.replace(/\/$/, '') })`.
+ **A new capability is missing from the client**: generate it again.
+ **`fetch` without `Accept: application/json`** to a `Route::action` or a controller route: it is a form request, and a write fails the CSRF check.
+ **An error shown as `[object Object]`**: show `e.message`, or `e.fields` for `invalid`.
## Related pages

+ [Build once: the JS client and tokens](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#client)
+ [Request](https://github.com/caligrafy/caligrafy-quill/wiki/3.-Request)
+ [Forms](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.4-Forms)

<br /><br />

> [Next Section: Forms](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.4-Forms)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.7.1-Understanding-the-structure -->

A Vue app made with `php caligrafer.php app` has two files of its own, and Caligrafy does the rest: it renders the markup through a page route, hands the page an `env` object with what the server knows (the application's address, the CSRF token, who is signed in, your `with` values), and loads your script. This page shows where each part lives and what the "handshake" between the server and the app does.
## With Claude

Claude follows this structure when it scaffolds or changes a Vue app (`/caligrafy-quill:new-app app <name>`). To understand an existing app, ask: "explain the structure of public/bookshelf and how it gets its data".

**Check** before you say OK:
+ The markup is a `.php` file in `public/<app>/`, the scripts are in `public/<app>/scripts/`.
+ The markup loads `scripts('vue')`, then `app.js`, then `loadEnvironment(...)`, then `loadVue(...)`, in this order.
+ Nothing from `application/` is linked from the page.
## By hand

You look inside the Bookshelf app of [Setting up Vue as a library](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.0-Setting-up-Vue.js-as-a-library) and read its `env`.

**1. The files.** Run `ls -R public/bookshelf`. Expected:
```text
index.php
scripts

public/bookshelf/scripts:
main.js
```

**2. The handshake in the markup.** The end of `public/bookshelf/index.php` holds four lines, in this order:
```php
<script src="<?php echo scripts('vue'); ?>"></script>
<script src="<?php echo APP_SERVICE_ROOT.'app.js?v='.@filemtime(PUBLIC_PATH.'js/services/app.js'); ?>"></script>
<script>loadEnvironment(`<?php echo $env; ?>`);</script>
<script>loadVue({ scripts: ['main'] });</script>
```
`scripts('vue')` is Vue 3; `app.js` (`public/js/services/app.js`, with a version in its address so a deploy reaches every browser) defines `loadEnvironment`, `loadVue` and `apiHeaders`; `$env` is the JSON the server prepared; `loadVue` adds `public/bookshelf/scripts/main.js` to the page.

**3. Read `env`.** Open `http://localhost:8080/bookshelf`, open the browser console and type `Object.keys(env)`. Expected:
```js
['appName', 'app', 'authorized', 'user', '__pug_adapter', 'scripts_version', 'app_root', 'service_root', 'app_resources', 'request', 'apiKey', 'token', 'csrf', 'home', 'keywords', 'metadata', 'copyright']
```
`env.home` is the application's address (`http://localhost:8080/`), `env.authorized` is `false` for a visitor, `env.user` is `null` (`__pug_adapter` is the view engine's own: ignore it). `Object.keys(env.request)` gives `['method', 'host', 'uri', 'fullUri', 'uriComponents', 'uriParameters', 'parameters', 'parsedURI', 'currentRoute', 'fetch', 'acceptLanguage']`: no header, no cookie (2.19.1).

**4. Pass your own value.** In `application/config/routing/web.php`, give the route a `with` value:
```php
    Route::page('/bookshelf', 'Client/app', ['with' => ['appName' => 'bookshelf', 'app' => 'index', 'shelf' => 'Science fiction']]);
```
Reload the page and type `env.shelf` in the console: `'Science fiction'`. In `main.js`, the script reads it as `env.shelf` (or `this.env.shelf`, since `data()` returns `env: env`).

**Check**
+ `env.home` ends with `/` and is the address of the application, also when `APP_ROOT` is not empty.
+ `env.csrf` is a 64-character token, the same as `env.token`.
+ `JSON.stringify(env.request)` contains no `Cookie`, no `Authorization` and no session id.
## Reference

### Folders

| Folder | What lives there |
| --- | --- |
| `application/` | the server: routes, capabilities, models, Pug views. Never served to browsers |
| `public/` | what browsers load: `css/`, `js/`, `images/`, and each client app in its own folder |
| `public/<app>/` | one Vue app: its markup (`index.php`, or other `.php` files), `scripts/` for its scripts; add `css/` or `images/` as needed |
| `public/js/capabilities.js` | the generated JS client, shared by every Vue app and the Pug pages |

### Why `.php` and not `.html`

The markup is included by the view `application/views/Client/app.pug`, so it runs as PHP: it can call `scripts()`, `session('public')`, `design_stylesheet()` and print `$env`. Write it as HTML with these few PHP lines; the rest is Vue.

### `env`

`application/views/Client/app.pug` builds `env` from every value the route gives the view, plus:

| Key | Value |
| --- | --- |
| `appName`, `app` | the app folder and the markup file (without `.php`) |
| your `with` values, `data` answers and route variables | as the route gives them |
| `authorized`, `user` | who is signed in (with `Route::page`) |
| `home` | the application's address, ending with `/` |
| `token`, `csrf` | the session's CSRF token (the same value) |
| `app_root`, `service_root`, `app_resources` | `public/app/`, `public/js/services/`, `public/resources/` as full addresses |
| `scripts_version` | the modification time of `public/js/services/app.js`: it changes at each deploy, and `loadVue()` adds it to the app's scripts (2.21.5) |
| `request` | what the page may see of the request that opened it, `request()->forClient()` (2.19.1): `method`, `host`, `uri`, `fullUri`, `uriComponents`, `uriParameters` (the query string, without `_token`), `parameters` (the query string, or the route variables when there is none), `parsedURI`, `currentRoute`, `fetch` (the route variables), `acceptLanguage`. Never the headers: no `Cookie` (the session id), no `Authorization`, and no POST body. Before 2.19.1 it was the whole request, headers included |
| `apiKey` | the legacy API key, or `null` when `LEGACY_API_KEY=false` (Caligrafy Cloud). Never use it in a page |
| `keywords`, `metadata`, `copyright` | the values of `application/config/config.php` |

`env` is printed inside `` loadEnvironment(`...`) ``: Caligrafy escapes it so any value, including one from the address, reaches your script unchanged and never runs as code.

### Globals of `public/js/services/app.js`

| Global | What it is |
| --- | --- |
| `env` | the object above |
| `csrfToken` | `env.csrf` |
| `apiHeaders(extra)` | `{ Accept: 'application/json', 'X-CSRF-Token': csrfToken }` merged with `extra`: the headers of a JSON call from the page to its own `Route::action` or controller routes |
| `apiKey` | `env.apiKey` (legacy) |
| `loadEnvironment(json)` | parses `env` |
| `loadVue({ scripts: [...] })` | adds `public/<appName>/scripts/<name>.js?v=<env.scripts_version>` for each name, in order (2.21.5: a browser never keeps the scripts of the deploy before) |

### The script

`main.js` creates the app with `Vue.createApp({...})`, registers its components with `app.component(...)`, then `app.mount('#app')`. Keep `env: env` in `data()` so the markup can use `env.home`.
## Other ways

`views/Client/app.pug` is the same for the bot, face detection and machine learning apps (`php caligrafer.php bot|facedetect|ml <name>`); their scaffolds differ in what they load.
## Common mistakes

+ **A script placed in `application/`**: the browser cannot load it. Scripts go in `public/<app>/scripts/`.
+ **`main.js` loaded before `loadEnvironment`**: `env` is `null`. Keep the order of step 2.
+ **A value expected in `env` that the route does not give**: add it to the route's `with`, or read it through a capability.
+ **Looking for a header or the cookie in `env.request`**: since 2.19.1 it has neither. Who is signed in is `env.user`; the CSRF token is `env.csrf`.
+ **A client app made before 2.21.6 with a bare `app.js` line**: a browser holding the old `app.js` never gets the script versions. Load it as in step 2, with `?v=`.
+ **Printing `env.apiKey` on screen**: it is the legacy key; never show or use it.
## Related pages

+ [Setting up Vue as a library](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.0-Setting-up-Vue.js-as-a-library)
+ [Routes](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.2-Routes)
+ [Requests](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.3-Requests)

<br/><br/>

> [Next Section: Learn more about Routes](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.2-Routes)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.7.4-Forms -->

A **form** in a Vue app collects what a person types and hands it to a capability. Vue keeps the fields in `data` (`v-model`), stops the browser from sending the form itself (`@submit.prevent`), and the generated client sends the values: no hidden `_token` field, no method spoofing, no request to build. The capability's rules answer, and the form shows each refusal under its field.
## With Claude

Ask for the form with the capability it calls: "in the bookshelf app, a form to add a book that shows each error under its field and a message when the book is added". Claude writes it in `public/<app>/index.php` and `scripts/main.js` with the page components (`.cq-form-grid`, `.cq-field`, `.cq-field-error`, `.cq-alert`).

**Check** before you say OK:
+ The `form` has `method="POST"` and `@submit.prevent`; the button is `type="submit"`.
+ Sending it empty shows one message under each required field; what was typed stays.
+ Sending it filled shows the success message once, and the fields are emptied.
+ The submit button cannot be pressed twice while the call runs.
## By hand

You finish the add form of the Bookshelf app of [Setting up Vue as a library](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.0-Setting-up-Vue.js-as-a-library): trimmed values, a length limit, a busy button and a success message.

**1. The form.** In `public/bookshelf/index.php`, replace the `cq-alert` line and the `form` with:
```html
                    <p class="cq-alert cq-alert--error" role="alert" v-if="error">{{ error }}</p>
                    <p class="cq-alert" role="status" v-if="message">{{ message }}</p>
                    <form method="POST" novalidate @submit.prevent="addBook">
                        <div class="cq-form-grid cq-form-grid--2">
                            <div class="cq-field">
                                <label for="title">Title</label>
                                <input id="title" class="form-control" type="text" maxlength="200" v-model.trim="book.title">
                                <p class="cq-field-error" v-if="errors.title">{{ errors.title }}</p>
                            </div>
                            <div class="cq-field">
                                <label for="author_id">Author</label>
                                <select id="author_id" class="form-select" v-model.number="book.author_id">
                                    <option v-for="author in authors" :key="author.id" :value="author.id">{{ author.name }}</option>
                                </select>
                                <p class="cq-field-error" v-if="errors.author_id">{{ errors.author_id }}</p>
                            </div>
                            <div class="cq-field">
                                <label for="published_year">Year</label>
                                <input id="published_year" class="form-control" type="number" v-model.number="book.published_year">
                                <p class="cq-field-error" v-if="errors.published_year">{{ errors.published_year }}</p>
                            </div>
                            <div class="cq-field">
                                <label for="summary">Summary</label>
                                <input id="summary" class="form-control" type="text" maxlength="2000" v-model.trim="book.summary">
                            </div>
                        </div>
                        <button class="btn btn-primary" type="submit" :disabled="sending">{{ sending ? 'Adding...' : 'Add book' }}</button>
                    </form>
```
+ `method="POST"`: if the script does not run, the browser never puts the fields in the address.
+ `novalidate`: the server's rules give the messages, the same as on the Pug page and over REST.
+ `@submit.prevent`: Vue calls `addBook` instead of the browser sending the form.
+ `v-model.trim`: the field's value, without spaces around it, in `book.title`; `v-model.number`: the year and the author's id as numbers, as the `integer` rules expect.
+ The Author list comes from `list_authors` (`this.authors`), each option's value an author's id.

**2. The script.** Replace `public/bookshelf/scripts/main.js` with:
```js
// Bookshelf: the books of the catalog, through the generated JS client (public/js/capabilities.js)
const app = Vue.createApp({
    data () {
        return {
            env: env,
            books: [], total: 0, page: 1, pages: 1,
            authors: [],
            book: { title: '', author_id: null, published_year: null, summary: '' },
            errors: {},
            error: '',
            message: '',
            sending: false
        }
    },
    async mounted () {
        this.api = await import(env.home + 'public/js/capabilities.js')
        this.api.configure({ baseUrl: env.home.replace(/\/$/, '') })   // the application root, whatever APP_ROOT is
        this.authors = await this.api.listAuthors()
        await this.load(1)
    },
    methods: {
        async load (page) {
            const result = await this.api.listBooks({ page: page })   // { data, total, page, per_page, pages }
            this.books = result.data
            this.total = result.total
            this.page = result.page
            this.pages = result.pages
        },
        async addBook () {
            this.errors = {}
            this.error = ''
            this.message = ''
            this.sending = true
            try {
                const created = await this.api.createBook(this.book)
                this.message = 'Book added: ' + created.title
                this.book = { title: '', author_id: null, published_year: null, summary: '' }
                await this.load(1)
            } catch (e) {
                if (e.name === 'CapabilityError' && e.code === 'invalid') this.errors = e.fields
                else this.error = e.message
            } finally {
                this.sending = false
            }
        }
    }
})

app.mount('#app')
```

**3. Try it.** Reload `http://localhost:8080/bookshelf`:
+ Press **Add book** with every field empty: `The Title field is required`, `The Author Id field is required` and `The Published Year field is required`, each under its field.
+ Type `  Imago  ` as the title, choose Octavia E. Butler, type `1989`, press **Add book**: `Book added: Imago` (without the spaces) above the form, the book in the list, the fields empty.

**Check**
+ The address bar never gets a `?` after sending.
+ The network panel shows one `POST /capabilities/create_book` per press, with a JSON body.
## Reference

| Part | Use |
| --- | --- |
| `form(method="POST" novalidate @submit.prevent="method")` | Vue handles the submit; the browser never sends it as a `GET` |
| `v-model`, `v-model.trim`, `v-model.number` | the value in `data`, trimmed, or as a number (for an `integer` rule) |
| `:disabled="sending"` | one call at a time |
| `e.fields` of a `CapabilityError` with `code === 'invalid'` | one message per field, keyed by the input's name |
| `.cq-form-grid`, `.cq-form-grid--2`, `.cq-field`, `p.cq-field-error`, `.cq-alert`, `.cq-alert--error` | the page components of a form ([Views](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#pagecomponents)) |

**Files.** The generated client sends JSON, so it cannot send a file. A capability with a `file` rule (`'cover' => 'required|file|extension,png;jpg|max_size,2mb'`) receives its file from a web form or REST: post a `FormData` to its [`Route::form`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form) address with `fetch(env.home + 'books', { method: 'POST', headers: apiHeaders(), body: formData })`. With `Accept: application/json` (in `apiHeaders()`), `Route::form` answers JSON instead of redirecting: `{"data": ...}` with `201`, or `{"error": {"code": "invalid", "fields": {...}}}` with `422`. See [file inputs](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#files).

Vue's own guides: [form bindings](https://vuejs.org/guide/essentials/forms.html), [event handling](https://vuejs.org/guide/essentials/event-handling.html), [conditional rendering](https://vuejs.org/guide/essentials/conditional.html), [list rendering](https://vuejs.org/guide/essentials/list.html).
## Other ways: form posts with `_token` and `_method`

A form request (without `Accept: application/json`) to a `Route::form`, a `Route::action` or a controller route must carry the session's CSRF token as the form field `_token`, or Caligrafy answers `403` (`[ERROR 3000]`). HTML forms only send `GET` and `POST`: a `_method` field turns a `POST` into a `PUT` or a `DELETE`.
```js
const formData = new FormData()
formData.append('title', 'Survivor')
formData.append('author_id', '2')
formData.append('published_year', '1978')
formData.append('_token', env.token)
const response = await fetch(env.home + 'books', { method: 'POST', body: formData })
// the Route::form of Views: redirected to /books/<id> (response.url); without _token: 403
```
For a route declared with `PUT` or `DELETE` (`Route::form('/books/{id}', 'update_book', ['method' => 'PUT'])`), add `formData.append('_method', 'PUT')` and keep `method: 'POST'`.
A Pug page writes the same fields with `= csrf()` and `= methodField('PUT')` ([Views: forms](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#formhelpers)). The generated client replaces this for capabilities; the token is read from form data only, never from a JSON body.
## Common mistakes

+ **No `method` on the form**: when the script fails to load, the browser sends the fields in the address (`GET /bookshelf?title=...`).
+ **Clearing the fields before the call answers**: a refused book would be lost. Clear them after success.
+ **`e.fields` shown for every error**: only `invalid` has fields; show `e.message` otherwise.
+ **A file field sent through `createBook()`**: JSON carries no file. Post a `FormData` to the `Route::form` address.
## Related pages

+ [Requests](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.3-Requests#capabilities)
+ [Validations](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.5-Validations)
+ [Declarative routes: `Route::form`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form)

<br /><br />

> [Next Section: Validations](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.5-Validations)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.7.6-Components -->

A **component** is a piece of a Vue screen with its own markup and behaviour, used like a new HTML tag: `<book-row>`, `<book-form>`. A parent passes data down to it through **props** and hears from it through **events**. In a Vue app as a library, components are registered in `scripts/main.js` with `app.component()`, and their markup lives in the `.php` file inside `<script type="text/x-template">` blocks. For larger apps, each component gets its own `.vue` file in a [single page app](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.3-Single-File-Components).
## With Claude

Ask for the split: "in the bookshelf app, make the book row and the add form two components; the page keeps the data and calls the capabilities". Claude registers them in `public/bookshelf/scripts/main.js` and puts their templates in `public/bookshelf/index.php`.

**Check** before you say OK:
+ Each component is registered with `app.component()` **before** `app.mount('#app')`.
+ Each template is a `<script type="text/x-template" id="...">` outside `<div id="app">`, with one root element.
+ Data flows down through props, and up through events declared in `emits`: a component never changes its props.
+ Only the page (the root app) calls the capabilities.
## By hand

You split the Bookshelf app of [Setting up Vue as a library](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.0-Setting-up-Vue.js-as-a-library) into two components: `book-row` shows one book, `book-form` keeps what is typed, gets the authors and the errors from the page, and sends an `add` event.

**1. The markup.** Replace `public/bookshelf/index.php` with:
```php
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
        <title>Bookshelf</title>
        <link rel="shortcut icon" href="<?php echo scripts('favicon'); ?>" type="image/x-icon" />
        <link rel="stylesheet" href="<?php echo scripts('bootstrap_css'); ?>" />
        <link rel="stylesheet" href="<?php echo session('public').'css/theme.css';?>">
        <link rel="stylesheet" href="<?php echo session('public').'css/tokens.css';?>">
        <link rel="stylesheet" href="<?php echo session('public').'css/layout.css';?>">
        <link rel="stylesheet" href="<?php echo session('public').'css/look.css';?>">
        <?php if (design_stylesheet()): ?><link rel="stylesheet" href="<?php echo design_stylesheet(); ?>"><?php endif; ?>
    </head>

    <body class="cq-site">
        <div id="app" v-cloak>
            <nav class="cq-nav" aria-label="Main">
                <a class="cq-nav-brand" :href="env.home"><img class="cq-nav-mark" :src="env.home + 'public/images/resources/caligrafy-mark.svg'" alt="" width="28" height="28"><span class="semibold">Book</span>shelf</a>
            </nav>
            <section class="cq-hero cq-hero--page">
                <h1 class="cq-display">Books</h1>
                <p class="cq-lead">{{ total }} books on the shelf.</p>
            </section>
            <section class="cq-band cq-band--tight">
                <div class="cq-inner cq-inner--narrow">
                    <p class="cq-alert cq-alert--error" role="alert" v-if="error">{{ error }}</p>
                    <book-form :authors="authors" :errors="errors" @add="addBook"></book-form>
                    <ul class="cq-rows" v-if="books.length">
                        <book-row v-for="item in books" :key="item.id" :book="item"></book-row>
                    </ul>
                    <p class="cq-empty-state" v-else>No books yet: add the first one above.</p>
                    <p v-if="pages > 1">
                        <button class="btn btn-secondary" type="button" :disabled="page === 1" @click="load(page - 1)">Previous</button>
                        <button class="btn btn-secondary" type="button" :disabled="page === pages" @click="load(page + 1)">Next</button>
                    </p>
                </div>
            </section>
        </div>

        <!-- TEMPLATES FOR VUE COMPONENTS -->
        <script type="text/x-template" id="book-row">
            <li class="cq-row">
                <div class="cq-row-main">
                    <p class="cq-row-title">{{ book.title }}</p>
                    <p class="cq-row-meta">{{ book.author.name }}, {{ book.published_year }}</p>
                </div>
            </li>
        </script>

        <script type="text/x-template" id="book-form">
            <form method="POST" novalidate @submit.prevent="submit">
                <div class="cq-form-grid cq-form-grid--2">
                    <div class="cq-field">
                        <label for="title">Title</label>
                        <input id="title" class="form-control" type="text" maxlength="200" v-model="book.title">
                        <p class="cq-field-error" v-if="errors.title">{{ errors.title }}</p>
                    </div>
                    <div class="cq-field">
                        <label for="author_id">Author</label>
                        <select id="author_id" class="form-select" v-model.number="book.author_id">
                            <option v-for="author in authors" :key="author.id" :value="author.id">{{ author.name }}</option>
                        </select>
                        <p class="cq-field-error" v-if="errors.author_id">{{ errors.author_id }}</p>
                    </div>
                    <div class="cq-field">
                        <label for="published_year">Year</label>
                        <input id="published_year" class="form-control" type="number" v-model.number="book.published_year">
                        <p class="cq-field-error" v-if="errors.published_year">{{ errors.published_year }}</p>
                    </div>
                    <div class="cq-field">
                        <label for="summary">Summary</label>
                        <input id="summary" class="form-control" type="text" maxlength="2000" v-model="book.summary">
                    </div>
                </div>
                <button class="btn btn-primary" type="submit">Add book</button>
            </form>
        </script>

        <script src="<?php echo scripts('vue'); ?>"></script>
        <script src="<?php echo APP_SERVICE_ROOT.'app.js?v='.@filemtime(PUBLIC_PATH.'js/services/app.js'); ?>"></script>
        <script>loadEnvironment(`<?php echo $env; ?>`);</script>
        <script>loadVue({ scripts: ['main'] });</script>
    </body>
</html>
```

**2. The script.** Replace `public/bookshelf/scripts/main.js` with:
```js
// Bookshelf: the books of the catalog, through the generated JS client (public/js/capabilities.js)
const app = Vue.createApp({
    data () {
        return {
            env: env,
            books: [], total: 0, page: 1, pages: 1,
            authors: [],
            errors: {},
            error: ''
        }
    },
    async mounted () {
        this.api = await import(env.home + 'public/js/capabilities.js')
        this.api.configure({ baseUrl: env.home.replace(/\/$/, '') })   // the application root, whatever APP_ROOT is
        this.authors = await this.api.listAuthors()
        await this.load(1)
    },
    methods: {
        async load (page) {
            const result = await this.api.listBooks({ page: page })   // { data, total, page, per_page, pages }
            this.books = result.data
            this.total = result.total
            this.page = result.page
            this.pages = result.pages
        },
        async addBook (book, done) {
            this.errors = {}
            this.error = ''
            try {
                await this.api.createBook(book)
                done()
                await this.load(1)
            } catch (e) {
                if (e.name === 'CapabilityError' && e.code === 'invalid') this.errors = e.fields
                else this.error = e.message
            }
        }
    }
})

// One book of the list: the parent passes it as a prop
app.component('book-row', {
    template: '#book-row',
    props: ['book']
})

// The form: it keeps what is typed, shows the errors the parent passes, and sends 'add' with the book
app.component('book-form', {
    template: '#book-form',
    props: ['authors', 'errors'],
    emits: ['add'],
    data () {
        return { book: { title: '', author_id: null, published_year: null, summary: '' } }
    },
    methods: {
        submit () {
            this.$emit('add', { ...this.book }, () => { this.book = { title: '', author_id: null, published_year: null, summary: '' } })
        }
    }
})

app.mount('#app')
```
The form sends a copy of the book and a `done` function; the page calls the capability and calls `done()` only when the book was added, so a refused book stays in the fields.

**3. Try it.** Reload `http://localhost:8080/bookshelf`:
+ The list shows the books, each drawn by `book-row`.
+ `Lilith` with Octavia E. Butler and no year: `The Published Year field is required` under the year (the page passed `errors` down), and the title stays.
+ With the year `1989`: the count goes up, *Lilith* is in the list and the fields empty.

**Check**
+ In the browser's element inspector, each row is a `li.cq-row` directly inside `ul.cq-rows`, and no `<book-row>` tag is left in the page (an unknown component stays as its tag).
+ The browser console shows no error other than the `422` of a refused book. (`scripts('vue')` is Vue's production build, which prints no development warnings.)
## Reference

| Property | What it is |
| --- | --- |
| `template` | `'#id'` of a `<script type="text/x-template" id="id">` in the markup, or the markup itself in a string |
| `props` | the values the parent passes: `props: ['book']`, used as `<book-row :book="item">` (`:` binds a value; without it the attribute is a fixed string) |
| `emits` | the events it sends: `emits: ['add']`, sent with `this.$emit('add', ...values)`, heard with `@add="addBook"` (the method gets the values) |
| `data()`, `methods`, `computed`, `watch`, `mounted()` | as for the app itself |
| slots | markup the parent places between the tags: `<slot></slot>` in the template, `<slot name="actions">` for a named one, filled with `<template v-slot:actions>` |

Register every component on the app returned by `Vue.createApp()`, before `app.mount('#app')`. A component name used in HTML markup is written in lowercase with dashes (`book-row`), because the browser reads `#app` as HTML before Vue does. A component's template has one root element.

Vue's guides: [components](https://vuejs.org/guide/essentials/component-basics.html), [props](https://vuejs.org/guide/components/props.html), [events](https://vuejs.org/guide/components/events.html), [slots](https://vuejs.org/guide/components/slots.html).
## Other ways

+ **The template in the script**: `template: '<li class="cq-row">...</li>'`. It works, and mixes markup into the script: keep templates in the markup file.
+ **`v-model` on a component** (`<book-title v-model="book.title">`): the component declares the prop `modelValue` and the event `update:modelValue`; see Vue's [component v-model](https://vuejs.org/guide/components/v-model.html).
## Common mistakes

+ **`app.component()` after `app.mount()`**: the tag stays unknown.
+ **A template inside `<div id="app">`**: Vue renders it as part of the page. Keep the `x-template` blocks after it.
+ **A component that changes its prop** (`this.errors = {}` in `book-form`): Vue warns and the parent's value does not change. Send an event; the parent changes its data.
+ **A component that calls the capabilities itself**: every row would call the server. Keep the calls in the page and pass the results down.
## Related pages

+ [Single file components](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.3-Single-File-Components)
+ [Forms](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.4-Forms)
+ [Views: page components](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#pagecomponents)

<br /><br />

**This is the end of the chapter on Vue as a library. For larger apps, continue with the [Vite single page app](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.1---Setting-up-the-Vue-application).**


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.8.1---Setting-up-the-Vue-application -->

A **single page app** (SPA) is a Vue app with its own routes between screens, `.vue` component files and a shared store, built with [Vite](https://vite.dev) into plain files. Caligrafy's template (`php caligrafer.php create`) gives you Vite 8, Vue 3.5, Vue Router 5 and Pinia, with Caligrafy's look already imported. The app lives in `public/<app>/`, calls your capabilities through the generated JS client, runs on Vite's development server while you work, and is served from `public/<app>/dist/` once built.
## With Claude

```text
/caligrafy-quill:new-app create shelfapp
```
Then describe the screens: "the list of the books with an add form, and a page for one book". Claude scaffolds the app, generates the client into `public/shelfapp/src/capabilities.js`, adds the `/capabilities` development proxy to `vite.config.js` and the books screens to the router, and writes the components with the page components. The template already has `base: './'`, hash addresses and no API key (2.19.1). It runs `npm install` on your computer, never in the Docker server (which has no Node.js).

**Check** before you say OK:
+ `npm run dev` opens the app and the books load; `npm run build` ends with `✓ built`.
+ `public/shelfapp/dist/index.html` opens from the Caligrafy server, and a reload of `#/books/1` shows the same book.
+ `src/main.js` has no `VITE_API_KEY` and no `Authorization` header: the built files contain no key.
## By hand

You create the Bookshelf single page app, `shelfapp`, run it in development, and build it. You need the Bookshelf tables and capabilities of [Views, steps 1 to 3](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#viewsstartup) and `Route::capabilities('/capabilities');` in `web.php`.

**1. Node.js.** On your computer, run `node --version`. It must be 20.19 or later in the 20 line, or 22.12 or later ([download](https://nodejs.org/en/download)). The Docker `dev-box` has no Node.js: run every `npm` command on your computer, in the project folder.

**2. Create the app.** Run, on your computer, from the project folder (this one command needs PHP 8.3+ on the computer, because `create` runs `npm install` where it runs):
```bash
php caligrafer.php create shelfapp
```
Expected, after npm's own lines:
```text
 VueJS project created and its packages installed.

 - To run the development server: cd public/shelfapp && npm run dev
 - To build it for production: npm run build (in the same folder)
```
With the Docker server instead (`docker compose exec dev-box php caligrafer.php create shelfapp`), it prints `VueJS project created, but its packages are NOT installed: npm is not available here (the Docker dev-box has no Node.js)`: then run `cd public/shelfapp && npm install` on your computer.

**3. The JS client.** Run:
```bash
docker compose exec dev-box php caligrafer.php client public/shelfapp/src/capabilities.js
```
Expected: `public/shelfapp/src/capabilities.js written: <n> capabilities, calls /capabilities ...`. Run it again after every change to a capability.

**4. The development proxy.** The template (2.19.1) already builds for any folder (`base: './'`), uses hash addresses (`createWebHashHistory()` in `src/router/index.js`), keeps no API key and commits `dist/`: nothing to change for those. What it does not have is a proxy for `npm run dev`: Vite's server runs on its own port (5173), so a call to `/capabilities` there answers `404` unless Vite forwards it to Caligrafy. Calling `http://localhost:8080` directly from port 5173 instead (`VITE_API_ROUTE`) is a call to another origin: the browser does not send the session cookie with the generated client's default (`credentials: 'same-origin'`). Replace `public/shelfapp/vite.config.js` with:
```js
import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'

// https://vite.dev/config/
export default defineConfig({
  // the built app works from any folder: public/shelfapp/dist/
  base: './',
  plugins: [
    vue(),
    vueDevTools(),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
  // npm run dev: the capability calls go to the Caligrafy server, with its session cookie
  server: {
    proxy: { '/capabilities': 'http://localhost:8080' }
  }
})
```
Use the address of your Caligrafy server in `proxy` (`http://localhost:8080` with Docker). The page and the proxied calls are then on one origin (`localhost:5173`), and the browser keeps one cookie per host whatever the port, so the session of `localhost:8080` goes with them.

<a name="router"></a>The router of the template, `public/shelfapp/src/router/index.js`, uses hash addresses (`#/books/3`) since 2.19.1: they work with `npm run dev` and in `dist/` from any folder, and survive a reload. Apps created before 2.19.1 use `createWebHistory()`: change it as [Routing for single page apps](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.2-Routing-for-Single-Page-Applications) shows, which also adds the books screens.

**5. Run it in development.** Start the Caligrafy server, then run:
```bash
cd public/shelfapp
npm run dev
```
Expected: `VITE v8.x.x  ready in ... ms` and `➜  Local:   http://localhost:5173/`. Open that address: the template's home, *Welcome to Caligrafy*, in Caligrafy's look. Every file you save shows at once. In the browser console, `(await import('/src/capabilities.js')).listBooks()` answers the books through the proxy.

**6. Build it.** Stop the development server (Ctrl+C) and run:
```bash
npm run build
```
Expected: three lines for `dist/index.html`, `dist/assets/index-<hash>.css` and `dist/assets/index-<hash>.js`, each with its size, then `✓ built in ...ms`. Open `http://localhost:8080/public/shelfapp/dist/index.html`: the same app, served by Caligrafy, calling `/capabilities` on the same server.

**Check**
+ `grep -rc VITE_API_KEY src` prints `0` for every file, and the files of `dist/assets/` contain no API key.
+ `http://localhost:8080/public/shelfapp/dist/index.html#/` reloads without an error.
+ `npm run lint` ends without errors (it fixes the formatting it can).
## <a name="capabilities"></a>Calling the capabilities of the application

A single page app is one more experience of your [capabilities](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#service): import the functions you need from the generated client.
```js
import { listBooks, createBook, CapabilityError } from '@/capabilities.js'

const page = await listBooks({ page: 1 })      // { data, total, page, per_page, pages }
try {
  await createBook({ title: 'Dawn', author_id: 2, published_year: 1987 })
} catch (e) {
  if (e instanceof CapabilityError && e.code === 'invalid') errors.value = e.fields
}
```
+ The client uses the visitor's session (cookie and CSRF token): nothing secret is built into the app.
+ In development the app runs on Vite's port and the proxy of step 4 forwards `/capabilities` to Caligrafy; the browser keeps one cookie for `localhost` whatever the port, so a person signed in on the Caligrafy server is signed in in the app.
+ Built, `dist/` is served by Caligrafy itself: the calls go to the same server. When the application is in a sub-folder (`APP_ROOT` not empty), call `configure({ baseUrl: '/<APP_ROOT>' })` once in `src/main.js`.
+ The [Requests reference](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.3-Requests#capabilities) lists every function, option and error.
## Reference

### The template (`framework/librairies/app`)

| File | What it is |
| --- | --- |
| `package.json` | scripts `dev` and `serve` (Vite's server), `host` (the same, open to your network), `build`, `preview` (serves `dist/`), `lint` (ESLint 10 with `--fix`); dependencies Vue 3.5, Vue Router 5, Pinia, axios 1.21; Node `^20.19.0 \|\| >=22.12.0`; `overrides` keeps `minimatch` 11 |
| `vite.config.js` | Vite 8, `base: './'` (2.19.1: `dist/` works from any folder), the Vue plugin, Vue devtools, the alias `@` = `src/`; no proxy (step 4 adds it) |
| `index.html` | the page: Bootstrap 5.3.9 from jsDelivr, `<div id="app">`, `src/main.js` |
| `src/main.js` | the app, Pinia, the router, Caligrafy's stylesheets from `public/css/`; `this.http` (axios), `this.config`, `this.apiConfig` and `this.apiHeaders` from `src/common/app.js` for every component |
| `src/App.vue` | the frame: the top bar, `<router-view>`, the footer |
| `src/router/index.js` | the routes, with `createWebHashHistory()` (2.19.1) |
| `src/common/store.js` | an example Pinia store ([State management](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.4-State-Management)) |
| `src/common/app.js` | axios settings for calls the generated client does not make (controller routes), 2.19.1: `config` (`apiRoute` = `VITE_API_ROUTE` or `''`, `capabilities` = `VITE_CAPABILITIES_ROUTE` or `/capabilities`), `csrfToken()` (reads `csrf` from `GET /capabilities` once), `apiHeaders(extra)` (`Accept: application/json` and `X-CSRF-Token`), `apiConfig` (JSON, `withCredentials: true`). No API key |
| `src/components/pages/`, `src/components/global/` | page components (`HomePage.vue`) and shared ones (`ShowNavigation.vue`, `ShowMessage.vue`, `ShowGeneralCard.vue`) |
| `.env` | `VITE_API_ROUTE=` (empty: the same site), written by `php caligrafer.php initialize` into the template and copied by `create`. No key since 2.19.1: everything in it ends up in the public build. Never committed (the project's `.gitignore` has `.env`) |
| `.gitignore` | `node_modules`, `dist-ssr`, logs and editor files; `dist/` is not ignored (2.19.1): it is committed |

`create <name>` copies the template to `public/<name>/`, then runs `npm install` when `npm` is found. The name must not be a folder Caligrafy uses in `public/` (`app`, `bot`, `__bots__`, `css`, `facedetect`, `fonts`, `images`, `js`, `ml`, `resources`, `uploads`), and `public/<name>/` must not exist yet.

### <a name="online"></a>Online

The production image of Caligrafy does not run `npm`: commit the built app.
1. Run `npm run build` in `public/shelfapp/`.
2. Commit `public/shelfapp/dist/` with the rest of the project (`node_modules/` stays out). The template's `.gitignore` does not ignore `dist/` since 2.19.1; in an app created before, delete the line `dist` from `public/shelfapp/.gitignore` first.
3. The app is at `https://<your site>/public/shelfapp/dist/index.html`, with hash addresses.

Build again and commit `dist/` after every change. A design style is imported in `src/main.js` (`import '../../css/designs/<name>.css'`) and needs a new build too.
## Other ways

+ **An address of its own** (`https://books.example.com/`): point a virtual host at `public/shelfapp/dist/`, keep `base: './'`, and set `configure({ baseUrl: 'https://<the Caligrafy address>' })` with a token, since the session cookie does not go to another site. With `createWebHistory()` instead of hash addresses, the virtual host needs a fallback to `index.html` (`FallbackResource /index.html`), or a reload of `/books/3` answers `404`.
+ **axios for a controller route** (one that answers with `api()`, not a capability): `this.http.post(this.config.apiRoute.replace(/\/+$/, '') + '/books/import', body, { headers: await this.apiHeaders(), withCredentials: true })` (an absolute path: the built app lives in `public/shelfapp/dist/`, so a relative `'books/import'` would point inside it), and add `'/books'` to the `proxy` of step 4 for `npm run dev`. The template sends the session and `X-CSRF-Token`, never an API key (2.19.1). Apps created before 2.19.1 have `'Bearer ' + VITE_API_KEY` in `src/main.js` and `src/common/app.js`: the key is readable by anyone in the built files and Caligrafy Cloud turns it off (`LEGACY_API_KEY=false`); replace both files with the template's.
## Common mistakes

+ **`npm install` reports 10 moderate vulnerabilities** (apps created with 2.2.0 or older): they come from `minimatch` below 11.0.1, used by ESLint only. Never run `npm audit fix --force` (it installs ESLint 4). Add `"overrides": { "minimatch": "^11.0.1" }` to `package.json`, then `rm -rf node_modules package-lock.json && npm install`.
+ **A blank page from `dist/`** (apps created before 2.19.1): the router uses `createWebHistory()`, or `base` is not `'./'` in `vite.config.js`. Use `createWebHashHistory()` and `base: './'`, as the template does now, and build again.
+ **`/capabilities` answers 404 in development**: the proxy of step 4 is missing or points to the wrong port.
+ **Changes not online**: `dist/` was not built again, or not committed.
## Related pages

+ [The flow of information](https://github.com/caligrafy/caligrafy-quill/wiki/9.7-Understanding-the-flow-of-information)
+ [Routing for single page apps](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.2-Routing-for-Single-Page-Applications)
+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)

<br/><br/>

> [Next Section: Routing for Single Page Applications](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.2-Routing-for-Single-Page-Applications)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.8.2-Routing-for-Single-Page-Applications -->

A single page app has one HTML page, and shows a different screen for each address: `#/` the list of the books, `#/books/3` one book. **Vue Router** maps each address to a page component; the page then asks the server for its data through the generated client. Caligrafy's server still answers the data (`Route::capabilities`) and serves the built app; the routes between screens live in `src/router/index.js`.
## With Claude

Ask for the screens and their addresses: "in shelfapp, the list of the books at #/ and one book at #/books/:id, each title a link". Claude writes the routes in `public/shelfapp/src/router/index.js`, the page components in `src/components/pages/`, and keeps hash addresses and the `:key` on `<router-view>`.

**Check** before you say OK:
+ The router uses `createWebHashHistory()`.
+ `App.vue` has `<router-view :key="$route.fullPath">`.
+ From one book, opening another (`#/books/1` then `#/books/3`) shows the second book.
+ A reload of `#/books/3` in the built app shows the same book.
## <a name="mainjs"></a>By hand

You give the Bookshelf app of [Setting up the Vue application](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.1---Setting-up-the-Vue-application) two screens. Files are in `public/shelfapp/`.

**1. The routes.** The template's router already uses hash addresses (`createWebHashHistory()`, 2.19.1); give it the two screens. Replace `src/router/index.js` with:
```js
import { createRouter, createWebHashHistory } from 'vue-router'
import BooksPage from '../components/pages/BooksPage.vue'
import BookPage from '../components/pages/BookPage.vue'

const router = createRouter({
  // #/books/3: works with npm run dev and in dist/, from any folder, and survives a reload
  history: createWebHashHistory(),
  routes: [
    { path: '/', name: 'books', component: BooksPage },
    { path: '/books/:id', name: 'book', component: BookPage, props: true }
  ]
})

export default router
```
`:id` is a parameter of the address; `props: true` gives it to the page as the prop `id`.

**2. The list.** Write `src/components/pages/BooksPage.vue`:
```vue
<template>
	<main>
		<section class='cq-hero cq-hero--page'>
			<h1 class='cq-display'>Books</h1>
			<p class='cq-lead'>{{ total }} books on the shelf.</p>
		</section>
		<section class='cq-band cq-band--tight'>
			<div class='cq-inner cq-inner--narrow'>
				<p class='cq-alert cq-alert--error' role='alert' v-if='error'>{{ error }}</p>
				<ul class='cq-rows' v-if='books.length'>
					<li class='cq-row' v-for='book in books' :key='book.id'>
						<div class='cq-row-main'>
							<p class='cq-row-title'>
								<router-link :to='{ name: "book", params: { id: book.id } }'>{{ book.title }}</router-link>
							</p>
							<p class='cq-row-meta'>{{ book.author.name }}, {{ book.published_year }}</p>
						</div>
					</li>
				</ul>
				<p class='cq-empty-state' v-else>No books yet.</p>
			</div>
		</section>
	</main>
</template>

<script>
import { listBooks } from '@/capabilities.js'

export default {
	name: 'books-page',
	data() {
		return { books: [], total: 0, error: '' }
	},
	async mounted() {
		try {
			const page = await listBooks({ page: 1 })   // { data, total, page, per_page, pages }
			this.books = page.data
			this.total = page.total
		} catch (e) {
			this.error = e.message
		}
	}
}
</script>
```

**3. One book.** Write `src/components/pages/BookPage.vue`:
```vue
<template>
	<main>
		<section class='cq-hero cq-hero--page'>
			<h1 class='cq-display'>{{ book ? book.title : 'Book' }}</h1>
			<p class='cq-lead' v-if='book'>by {{ book.author.name }}, {{ book.published_year }}</p>
		</section>
		<section class='cq-band cq-band--tight'>
			<div class='cq-inner cq-inner--narrow'>
				<p class='cq-alert cq-alert--error' role='alert' v-if='error'>{{ error }}</p>
				<p v-if='book'>{{ book.summary || 'No summary yet.' }}</p>
				<p><router-link class='btn btn-secondary' :to='{ name: "books" }'>All books</router-link></p>
			</div>
		</section>
	</main>
</template>

<script>
import { getBook } from '@/capabilities.js'

export default {
	name: 'book-page',
	props: ['id'],
	data() {
		return { book: null, error: '' }
	},
	async mounted() {
		try {
			this.book = await getBook({ id: this.id })   // the book, with its author in book.author
		} catch (e) {
			this.error = e.message
		}
	}
}
</script>
```

**4. The frame.** Replace `src/App.vue` with (the template's, plus the `:key`):
```vue
<template>
	<show-navigation></show-navigation>
	<router-view :key="$route.fullPath"></router-view>
	<footer class='cq-footer'>
		<p>Copyright &copy; {{ new Date().getFullYear() }}</p>
	</footer>
</template>

<script>
import ShowNavigation from './components/global/ShowNavigation.vue'

export default {
	name: 'App',
	components: {
		'show-navigation': ShowNavigation
	}
}
</script>
```
The `:key` gives every address a fresh page: without it, going from `#/books/1` to `#/books/3` reuses the same `BookPage`, `mounted()` does not run again, and book 1 stays on screen.

**5. The top bar link.** In `src/components/global/ShowNavigation.vue`, the brand links to the old home: replace `:to='{ name: "home" }'` with `:to='{ name: "books" }'`. Then delete `src/components/pages/HomePage.vue` (nothing imports it any more).

**6. Try it.** Run `npm run build`, then open `http://localhost:8080/public/shelfapp/dist/index.html`:
+ The list says `5 books on the shelf.` and shows them sorted by title, each with its author and year; *A Wizard of Earthsea* links to `#/books/1`.
+ Click *Kindred*: the address becomes `#/books/3` and the page shows `Kindred`, `by Octavia E. Butler, 1979` and its summary.
+ Change the address to `#/books/1`: the page shows *A Wizard of Earthsea*. Reload: still the same book.
+ `#/books/999` shows `There is no book #999`.

**Check**
+ `npm run dev` gives the same screens at `http://localhost:5173/#/`.
+ The address bar never leaves `index.html`: every screen is after the `#`.
## Reference

| Part | Use |
| --- | --- |
| `createRouter({ history, routes })` | the router, installed by `app.use(router)` in `src/main.js` |
| `createWebHashHistory()` | addresses after a `#`: they work in development and in `dist/` from any folder, and survive a reload |
| `{ path, name, component }` | one screen; `name` lets links say `{ name: 'book', params: { id: 3 } }` instead of building the address |
| `path: '/books/:id'` | a parameter, read with `this.$route.params.id`, or as the prop `id` with `props: true` |
| `component: () => import('../components/pages/BookPage.vue')` | loads the page only when it is opened (a separate file in `dist/assets/`) |
| `<router-link :to="{ name: 'book', params: { id } }">` | a link between screens, without reloading |
| `this.$router.push({ name: 'book', params: { id } })` | goes to a screen from code (after a form, for example) |
| `<router-view :key="$route.fullPath">` | where the screen of the address appears, rebuilt for every address |
| `useRoute()`, `useRouter()` | the same in `<script setup>` components: `import { useRoute } from 'vue-router'` |

The server's routes and the app's routes are separate: `web.php` answers `/capabilities` and serves the files of `dist/`; the router chooses the screen from the part after `#`. See [Vue Router](https://router.vuejs.org/).
## Other ways

+ **Addresses without `#`** (`createWebHistory()`, the template's default before 2.19.1): `/books/3` works with `npm run dev`, but a reload asks the server for `/books/3`. The built app then needs its own site (a virtual host on `dist/` with `FallbackResource /index.html`, and `base` set to its path), or a reload answers `404`. Under `public/<app>/dist/`, keep hash addresses.
+ **Watching the parameter** instead of the `:key`: `watch: { id() { this.load() } }` in the page, when rebuilding the whole page is too much.
## Common mistakes

+ **A blank screen in `dist/`**: `createWebHistory()` with the app in a sub-folder (apps created before 2.19.1). Use `createWebHashHistory()`, as the template does since 2.19.1.
+ **The previous book stays on screen**: `<router-view>` without `:key="$route.fullPath"`.
+ **A route to a component that is not imported**: Vite stops the build (`Could not resolve`). Import every page the routes name, or use `() => import(...)`.
+ **Expecting `web.php` to know `#/books/3`**: the browser never sends the part after `#` to the server.
## Related pages

+ [Setting up the Vue application](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.1---Setting-up-the-Vue-application)
+ [Single file components](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.3-Single-File-Components)
+ [Routes of a Vue app as a library](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.2-Routes)

<br/><br/>

> [Next Section: Single File Components (SFC)](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.3-Single-File-Components)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.8.3-Single-File-Components -->

A **single file component** is one `.vue` file that holds a piece of the screen: its markup (`<template>`), its behaviour (`<script>`) and, when it needs one, its style (`<style>`). Vite turns these files into the built app. In a Caligrafy single page app, the screens of the router are **page** components (`src/components/pages/`), and pieces used on several screens are **global** components (`src/components/global/`). A parent passes data down through **props** and hears from a child through **events**.
## With Claude

Ask for the piece and who uses it: "in shelfapp, make the add form a component BookForm that shows the errors the page gives it and sends the book to the page; after adding, open the new book". Claude writes `src/components/global/BookForm.vue` and changes `src/components/pages/BooksPage.vue`.

**Check** before you say OK:
+ The child declares its `props` and `emits`; it never changes a prop.
+ Only page components (or the store) call the capabilities.
+ The markup uses the page components (`.cq-form-grid`, `.cq-field`, `.cq-field-error`), with no `<style>` for what they already do.
+ `npm run build` ends with `✓ built`.
## By hand

You add a form component to the Bookshelf app of [Routing for single page apps](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.2-Routing-for-Single-Page-Applications). Files are in `public/shelfapp/`.

**1. The child.** Write `src/components/global/BookForm.vue`:
```vue
<template>
	<form method='POST' novalidate @submit.prevent='submit'>
		<div class='cq-form-grid cq-form-grid--2'>
			<div class='cq-field'>
				<label for='title'>Title</label>
				<input id='title' class='form-control' type='text' maxlength='200' v-model.trim='book.title'>
				<p class='cq-field-error' v-if='errors.title'>{{ errors.title }}</p>
			</div>
			<div class='cq-field'>
				<label for='author_id'>Author</label>
				<select id='author_id' class='form-select' v-model.number='book.author_id'>
					<option v-for='author in authors' :key='author.id' :value='author.id'>{{ author.name }}</option>
				</select>
				<p class='cq-field-error' v-if='errors.author_id'>{{ errors.author_id }}</p>
			</div>
			<div class='cq-field'>
				<label for='published_year'>Year</label>
				<input id='published_year' class='form-control' type='number' v-model.number='book.published_year'>
				<p class='cq-field-error' v-if='errors.published_year'>{{ errors.published_year }}</p>
			</div>
			<div class='cq-field'>
				<label for='summary'>Summary</label>
				<input id='summary' class='form-control' type='text' maxlength='2000' v-model.trim='book.summary'>
			</div>
		</div>
		<button class='btn btn-primary' type='submit'>Add book</button>
	</form>
</template>

<script>
export default {
	name: 'book-form',
	props: {
		authors: { type: Array, default: () => [] },
		errors: { type: Object, default: () => ({}) }
	},
	emits: ['add'],
	data() {
		return { book: { title: '', author_id: null, published_year: null, summary: '' } }
	},
	methods: {
		submit() {
			this.$emit('add', { ...this.book })
		}
	}
}
</script>
```
It keeps what is typed, lists the `authors` and shows the `errors` its parent passes, and sends a copy of the book with the `add` event.

**2. The parent.** Replace `src/components/pages/BooksPage.vue` with:
```vue
<template>
	<main>
		<section class='cq-hero cq-hero--page'>
			<h1 class='cq-display'>Books</h1>
			<p class='cq-lead'>{{ total }} books on the shelf.</p>
		</section>
		<section class='cq-band cq-band--tight'>
			<div class='cq-inner cq-inner--narrow'>
				<p class='cq-alert cq-alert--error' role='alert' v-if='error'>{{ error }}</p>
				<book-form :authors='authors' :errors='errors' @add='addBook'></book-form>
				<ul class='cq-rows' v-if='books.length'>
					<li class='cq-row' v-for='book in books' :key='book.id'>
						<div class='cq-row-main'>
							<p class='cq-row-title'>
								<router-link :to='{ name: "book", params: { id: book.id } }'>{{ book.title }}</router-link>
							</p>
							<p class='cq-row-meta'>{{ book.author.name }}, {{ book.published_year }}</p>
						</div>
					</li>
				</ul>
				<p class='cq-empty-state' v-else>No books yet: add the first one above.</p>
			</div>
		</section>
	</main>
</template>

<script>
import { listBooks, listAuthors, createBook, CapabilityError } from '@/capabilities.js'
import BookForm from '../global/BookForm.vue'

export default {
	name: 'books-page',
	components: {
		'book-form': BookForm
	},
	data() {
		return { books: [], total: 0, authors: [], errors: {}, error: '' }
	},
	async mounted() {
		try {
			this.authors = await listAuthors()
			const page = await listBooks({ page: 1 })
			this.books = page.data
			this.total = page.total
		} catch (e) {
			this.error = e.message
		}
	},
	methods: {
		async addBook(book) {
			this.errors = {}
			this.error = ''
			try {
				const created = await createBook(book)
				this.$router.push({ name: 'book', params: { id: created.id } })
			} catch (e) {
				if (e instanceof CapabilityError && e.code === 'invalid') this.errors = e.fields
				else this.error = e.message
			}
		}
	}
}
</script>
```

**3. Try it.** Run `npm run dev` and open `http://localhost:5173/#/` (or `npm run build` and `http://localhost:8080/public/shelfapp/dist/index.html`):
+ Type `Mind of My Mind`, choose Octavia E. Butler, no year, press **Add book**: `The Published Year field is required` under the year; the title stays.
+ Type `1977` and press **Add book**: the address becomes `#/books/6` and the page shows *Mind of My Mind*, `by Octavia E. Butler, 1977`.

**Check**
+ `BookForm.vue` imports nothing from `capabilities.js`.
+ `npm run build` ends with `✓ built`.
## Reference

### The parts of a `.vue` file

| Part | What it holds |
| --- | --- |
| `<template>` | the markup, with Vue's syntax (`{{ }}`, `v-if`, `v-for`, `v-model`, `:prop`, `@event`) |
| `<script>` | `export default { name, components, props, emits, data(), computed, watch, mounted(), methods }`, and the `import`s it needs |
| `<style>` | its own CSS when the page components do not cover it; `<style scoped>` keeps it to this component |

`@` is the `src/` folder (the alias of `vite.config.js`): `import BookForm from '@/components/global/BookForm.vue'`.

### Kinds of components

| Kind | Where | Example |
| --- | --- | --- |
| frame | `src/App.vue` | the top bar, `<router-view>`, the footer |
| page | `src/components/pages/` | `BooksPage.vue`, `BookPage.vue`: named by the routes |
| global | `src/components/global/` | `ShowNavigation.vue`, `BookForm.vue`: used by several pages |

### Talking between components

| Direction | How |
| --- | --- |
| parent to child | props: `props: { errors: { type: Object, default: () => ({}) } }` in the child, `<book-form :errors="errors">` in the parent |
| child to parent | events: `emits: ['add']` and `this.$emit('add', book)` in the child, `<book-form @add="addBook">` in the parent (the method gets `book`) |
| markup from the parent | slots: `<slot></slot>` in the child's template |
| between any components | a store ([State management](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.4-State-Management)) |

Vue's guides: [single file components](https://vuejs.org/guide/scaling-up/sfc.html), [props](https://vuejs.org/guide/components/props.html), [events](https://vuejs.org/guide/components/events.html), [slots](https://vuejs.org/guide/components/slots.html).
## Other ways

+ **The Composition API** (`<script setup>`): the same component written with `defineProps`, `defineEmits` and `ref`:
  ```vue
  <script setup>
  import { ref } from 'vue'
  defineProps({
    authors: { type: Array, default: () => [] },
    errors: { type: Object, default: () => ({}) }
  })
  const emit = defineEmits(['add'])
  const book = ref({ title: '', author_id: null, published_year: null, summary: '' })
  function submit() { emit('add', { ...book.value }) }
  </script>
  ```
  The template is the same. Pick one style per app; this wiki uses the Options API of the template.
## Common mistakes

+ **A component that changes its prop** (`this.errors = {}` in `BookForm`): Vue warns in development and the parent's value does not change. Send an event.
+ **Forgetting `components: { 'book-form': BookForm }`** in the parent: the tag stays unknown (a warning in `npm run dev`).
+ **An event not in `emits`**: it still works, but Vue also passes the listener to the root element; declare every event.
+ **A `<style>` that copies the page components**: use their classes, so the app keeps Caligrafy's look and its design style.
## Related pages

+ [Components in a Vue app as a library](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.6-Components)
+ [Routing for single page apps](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.2-Routing-for-Single-Page-Applications)
+ [State management](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.4-State-Management)

<br/><br/>

> [Next Section: State Management](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.4-State-Management)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.8.4-State-Management -->

**State management** keeps the data that several components share in one place, a **store**, so every component shows the same thing and changes it the same way. Caligrafy's single page app template uses [Pinia](https://pinia.vuejs.org/), the official store of Vue (it replaces Vuex): `src/main.js` installs it (`app.use(createPinia())`) and `src/common/store.js` holds an example. In a Caligrafy app, the store's actions call the capabilities, so the store also holds what the server answered: the books, their count, the field errors.
## With Claude

Ask for what is shared: "in shelfapp, keep the books, the authors and the form errors in a Pinia store; the top bar shows how many books there are". Claude writes the store in `public/shelfapp/src/common/store.js`, with actions that call the generated client, and changes the components to read it.

**Check** before you say OK:
+ Only the store's actions call the capabilities; the components call the actions.
+ After adding a book, the count in the top bar and in the list change together, without a reload.
+ `npm run build` ends with `✓ built`.
## By hand

You move the data of the Bookshelf app of [Single file components](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.3-Single-File-Components) into a store, and show the count of books in the top bar. Files are in `public/shelfapp/`.

**1. The store.** Replace `src/common/store.js` with:
```js
import { defineStore } from 'pinia'
import { listBooks, listAuthors, createBook, CapabilityError } from '@/capabilities.js'

export const useBooksStore = defineStore('books', {
    // shared data
    state: () => ({
        books: [],
        total: 0,
        page: 1,
        pages: 1,
        authors: [],
        errors: {},
        error: ''
    }),

    // values computed from the state
    getters: {
        isEmpty: (state) => state.total === 0
    },

    // what changes the state: here, through the capabilities
    actions: {
        async load(page = 1) {
            try {
                if (!this.authors.length) this.authors = await listAuthors()
                const result = await listBooks({ page })   // { data, total, page, per_page, pages }
                this.books = result.data
                this.total = result.total
                this.page = result.page
                this.pages = result.pages
            } catch (e) {
                this.error = e.message
            }
        },
        async add(book) {
            this.errors = {}
            this.error = ''
            try {
                const created = await createBook(book)
                await this.load(1)
                return created
            } catch (e) {
                if (e instanceof CapabilityError && e.code === 'invalid') this.errors = e.fields
                else this.error = e.message
                return null
            }
        }
    }
})
```

**2. The top bar loads it.** The top bar is on every screen, so it loads the books once for the whole app. Replace `src/components/global/ShowNavigation.vue` with:
```vue
<template>
	<nav class='cq-nav' aria-label='Main'>
		<router-link class='cq-nav-brand' :to='{ name: "books" }'>
			<img class='cq-nav-mark' :src='mark' alt='' width='28' height='28'>
			<span class='semibold'>Book</span><span>shelf</span>
		</router-link>
		<div class='cq-nav-links'>
			<router-link class='cq-nav-link' :to='{ name: "books" }'>{{ store.total }} books</router-link>
		</div>
	</nav>
</template>

<script>
import mark from '../../assets/caligrafy-mark.svg'
import { useBooksStore } from '@/common/store'

export default {
	name: 'show-navigation',
	data() {
		return { mark, store: useBooksStore() }
	},
	mounted() {
		// the top bar is on every screen: it loads the books once for the whole app
		this.store.load(1)
	}
}
</script>
```

**3. The form uses it.** Replace `src/components/global/BookForm.vue` with:
```vue
<template>
	<form method='POST' novalidate @submit.prevent='submit'>
		<div class='cq-form-grid cq-form-grid--2'>
			<div class='cq-field'>
				<label for='title'>Title</label>
				<input id='title' class='form-control' type='text' maxlength='200' v-model.trim='book.title'>
				<p class='cq-field-error' v-if='store.errors.title'>{{ store.errors.title }}</p>
			</div>
			<div class='cq-field'>
				<label for='author_id'>Author</label>
				<select id='author_id' class='form-select' v-model.number='book.author_id'>
					<option v-for='author in store.authors' :key='author.id' :value='author.id'>{{ author.name }}</option>
				</select>
				<p class='cq-field-error' v-if='store.errors.author_id'>{{ store.errors.author_id }}</p>
			</div>
			<div class='cq-field'>
				<label for='published_year'>Year</label>
				<input id='published_year' class='form-control' type='number' v-model.number='book.published_year'>
				<p class='cq-field-error' v-if='store.errors.published_year'>{{ store.errors.published_year }}</p>
			</div>
			<div class='cq-field'>
				<label for='summary'>Summary</label>
				<input id='summary' class='form-control' type='text' maxlength='2000' v-model.trim='book.summary'>
			</div>
		</div>
		<button class='btn btn-primary' type='submit'>Add book</button>
	</form>
</template>

<script>
import { useBooksStore } from '@/common/store'

export default {
	name: 'book-form',
	emits: ['added'],
	data() {
		return {
			store: useBooksStore(),
			book: { title: '', author_id: null, published_year: null, summary: '' }
		}
	},
	methods: {
		async submit() {
			const created = await this.store.add(this.book)
			if (created) {
				this.book = { title: '', author_id: null, published_year: null, summary: '' }
				this.$emit('added', created)
			}
		}
	}
}
</script>
```
The form calls the store's `add` action, reads the errors from the store, and tells the page when a book was added.

**4. The list uses it.** Replace `src/components/pages/BooksPage.vue` with:
```vue
<template>
	<main>
		<section class='cq-hero cq-hero--page'>
			<h1 class='cq-display'>Books</h1>
			<p class='cq-lead'>{{ store.total }} books on the shelf.</p>
		</section>
		<section class='cq-band cq-band--tight'>
			<div class='cq-inner cq-inner--narrow'>
				<p class='cq-alert cq-alert--error' role='alert' v-if='store.error'>{{ store.error }}</p>
				<book-form @added='open'></book-form>
				<ul class='cq-rows' v-if='!store.isEmpty'>
					<li class='cq-row' v-for='book in store.books' :key='book.id'>
						<div class='cq-row-main'>
							<p class='cq-row-title'>
								<router-link :to='{ name: "book", params: { id: book.id } }'>{{ book.title }}</router-link>
							</p>
							<p class='cq-row-meta'>{{ book.author.name }}, {{ book.published_year }}</p>
						</div>
					</li>
				</ul>
				<p class='cq-empty-state' v-else>No books yet: add the first one above.</p>
			</div>
		</section>
	</main>
</template>

<script>
import { useBooksStore } from '@/common/store'
import BookForm from '../global/BookForm.vue'

export default {
	name: 'books-page',
	components: {
		'book-form': BookForm
	},
	data() {
		return {
			store: useBooksStore()
		}
	},
	methods: {
		open(book) {
			this.$router.push({ name: 'book', params: { id: book.id } })
		}
	}
}
</script>
```
The page no longer loads anything: the top bar did, and the list reads the store.

**5. Try it.** Run `npm run build`, then open `http://localhost:8080/public/shelfapp/dist/index.html#/books/3`:
+ The top bar says `5 books` on the page of *Kindred*: the store was loaded by the top bar.
+ Click `5 books`: the list shows the same books and the Author list its three authors, with no new call to `list_books` (the network panel shows none).
+ Type `Bloodchild`, choose Octavia E. Butler, no year, press **Add book**: `The Published Year field is required` under the year.
+ Type `1995` and press **Add book**: the address becomes `#/books/6`, and the top bar says `6 books`.

**Check**
+ `BooksPage.vue` and `BookForm.vue` import nothing from `capabilities.js`.
+ The count in the top bar and in the title band of the list are always the same.
## Reference

### A store

`defineStore(id, { state, getters, actions })` returns a function; call it in a component to get the store (`useBooksStore()`). Every component that calls it gets the same store.

| Part | What it is | Use |
| --- | --- | --- |
| `state: () => ({...})` | the shared data and its first values | `store.books`, `store.total`; change it in place (`store.total++`), several at once with `store.$patch({ page: 2 })`; `store.$reset()` restores the first values |
| `getters` | values computed from the state, kept until the state they read changes | `store.isEmpty`; a getter that takes an argument returns a function: `byAuthor: (state) => (id) => state.books.filter(b => b.author_id === id)` |
| `actions` | methods that change the state, synchronous or `async`; `this` is the store | `await store.load(2)`, `await store.add(book)` |

In an Options API component, keep the store in `data()` (`store: useBooksStore()`) and read it in the template (`store.total`). In a `<script setup>` component: `const store = useBooksStore()`. You can have as many stores as you need, one per subject (books, the signed-in person, a cart), each with its own id.

### Stores and capabilities

| In the store | Comes from |
| --- | --- |
| `books`, `total`, `page`, `pages` | `listBooks({ page })`: `{ data, total, page, per_page, pages }` |
| `authors` | `listAuthors()` |
| `errors` | `e.fields` of a `CapabilityError` with `code === 'invalid'` |
| `error` | `e.message` of any other refusal |

The store holds a copy of what the server answered. Load it again (`store.load(1)`) when the data may have changed elsewhere: another person, the REST API or an AI agent.

### Migrating from Vuex

| Vuex | Pinia |
| --- | --- |
| `createStore({ state, mutations, actions, getters })` | `defineStore('id', { state: () => ({...}), getters, actions })` |
| `app.use(store)` | `app.use(createPinia())` |
| `this.$store.state.count` | `store.count` (with `const store = useBooksStore()`) |
| `this.$store.commit('increment', 1)` (a mutation) | `store.increment(1)` (an action) or `store.count++`: there are no mutations |
| `this.$store.dispatch('load', 1)` | `store.load(1)` |
| `this.$store.getters.isEmpty` | `store.isEmpty` |
## Other ways

+ **No store**: for one or two screens, the page component keeps the data and passes it down with props, as in [Single file components](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.3-Single-File-Components). Add a store when two components that are not parent and child need the same data.
+ **The template's example store** (`useAppStore`, a counter with `count`, `isEven` and `increment`) shows the three parts with no server: replace it with stores of your own.
## Common mistakes

+ **`useBooksStore()` outside a component, before `app.use(createPinia())`**: Pinia is not installed yet. Call it in `data()` or `setup`.
+ **Copying a store value into a component's own data** (`total: store.total`): the copy does not follow the store. Read `store.total` in the template.
+ **A component that calls a capability and also the store**: two copies of the same data. Let the store's actions call the capabilities.
+ **Expecting the store to survive a reload**: it lives in the page. A reload loads it again from the server.
## Related pages

+ [Pinia](https://pinia.vuejs.org/)
+ [Requests: the generated client](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.3-Requests#capabilities)
+ [Setting up the Vue application](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.1---Setting-up-the-Vue-application)

<br /><br />

**This is the end of the Caligrafy Vue documentation. Next: [put your application online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online).**


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/REST-API -->

The **REST API** of a Caligrafy application is its capabilities, answered in JSON. One line maps a route to a
capability (`Route::capability`), or one line serves them all by name (`Route::capabilities`). Programs send a personal
access token; pages of the application send the session and its CSRF token. Since 2.1.0.
## With Claude

```text
/caligrafy-quill:new-capability create_book books:write: add a book and return it; serve it as POST /api/books
```

Claude adds the `Route::capability` line to `web.php` and checks it with `curl`: without a token, with a token that lacks
the scope, and with a good one.

**Check** before you say OK: the calls answer `401`, `403` and `201` as below.
## By hand

1. **The routes.** In `application/config/routing/web.php`, before `Route::run();`:
    ```php
    // BOOKSHELF: REST
    Route::capability('GET', '/api/books', 'list_books');
    Route::capability('GET', '/api/books/{id}', 'get_book');
    Route::capability('POST', '/api/books', 'create_book');
    Route::capability('DELETE', '/api/books/{id}', 'delete_book');
    ```
    The method is `GET`, `POST`, `PUT` or `DELETE`. The route variables (`{id}`) become inputs.
2. **A token** for the program: `php caligrafer.php token create "Bookshelf agent" --scopes books:read,books:write`
   ([Personal access tokens](https://github.com/caligrafy/caligrafy-quill/wiki/Personal-Access-Tokens)).
3. **Call it.**
    ```bash
    curl -s http://localhost:8080/api/books/3
    # {"data":{"id":3,"title":"Kindred","published_year":1979,...}}            200: get_book is public

    curl -s -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d '{"title": "Dune"}' http://localhost:8080/api/books
    # {"error":{"code":"unauthenticated","message":"Sign in or send a personal access token"}}   401

    curl -s -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" \
         -d '{"title": "The Lathe of Heaven", "published_year": 1971, "author_id": 1}' http://localhost:8080/api/books
    # {"data":{"id":7,"title":"The Lathe of Heaven",...}}   201
    ```
    A `POST` with neither a token nor `Accept: application/json` is taken for a form and answers `403` `[ERROR 3000]`.
## <a name="all"></a>Every capability by name: `Route::capabilities`

```php
Route::capabilities('/capabilities');   // GET lists, POST /capabilities/{name} calls
```

+ `GET /capabilities` answers what the caller may call, with the input schemas, and the session's CSRF token:
  `{"data": [{"name", "description", "scope", "level", "readOnly", "destructive", "public", "input"}, ...], "csrf": "..."}`.
  Web-only capabilities are left out.
+ `POST /capabilities/get_book` with `{"id": 3}` calls `get_book`. The
  [JS client](https://github.com/caligrafy/caligrafy-quill/wiki/The-JS-Client) uses these two routes.
## <a name="reference"></a>Requests and responses

**Who calls** (`Context::fromRequest`): `Authorization: Bearer cq_...` (a token), else the legacy API key, else the
session of a signed-in person, else a visitor.

**Inputs**: the JSON body, or the form fields, or the query string for `GET`; then the route variables, which win
(`/api/books/3?id=9` is the book 3). `_token`, `_method` and `uri` are never inputs. Of the inputs, the capability keeps
only those of its `$rules`.

**Files**: a capability with a `file` input takes a multipart upload; the file is saved once the caller is allowed, and
deleted again when the call fails.

**CSRF**: a call made with the session cookie that is not read-only needs the session's CSRF token in an `X-CSRF-Token`
header (or `_token`), else `403` "Missing or invalid CSRF token: send the X-CSRF-Token header". A token or the legacy key
is not a cookie, so it needs none.

**Responses**:

| Status | Body | When |
| --- | --- | --- |
| `200` | `{"data": ...}` | a success |
| `201` | `{"data": ...}` | a `POST` to a capability that is not read-only |
| `401` | `{"error": {"code": "unauthenticated", "message": ...}}`, and `WWW-Authenticate: Bearer` | nobody, or an unknown, revoked or expired token |
| `403` | `{"error": {"code": "forbidden", ...}}` | the scope or the level is missing, or the CSRF token |
| `404` | `{"error": {"code": "not_found", ...}}` | no such capability, or the thing does not exist |
| `409` | `{"error": {"code": "conflict", ...}}` | it clashes with the current state |
| `422` | `{"error": {"code": "invalid", "message": ..., "fields": {...}}}` | an input is wrong, a message per field |

The data is plain: models become arrays of their columns. All the refusals:
[Refusing a call](https://github.com/caligrafy/caligrafy-quill/wiki/Refusing-a-Call-ServiceError).

Reference: [`Route::capability()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-capability),
[`Route::capabilities()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-capabilities),
[`Rest`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#rest).
## Common mistakes

+ **A write over the session without `X-CSRF-Token`** (G54): 403. Use the JS client, or send the `csrf` of `GET /capabilities`.
+ **A JSON call from a page without `Accept: application/json`** (G1): it is taken for a form and fails CSRF, `[ERROR 3000]`.
+ **`register_user` over REST** (G81): refused; sign-up is the sign-up page.
+ **A closure route for JSON** (G51): `Route::post('/x', function () {...})` is not protected for JSON. Use a capability route.
## Related pages

+ [The JS client](https://github.com/caligrafy/caligrafy-quill/wiki/The-JS-Client) · [Personal access tokens](https://github.com/caligrafy/caligrafy-quill/wiki/Personal-Access-Tokens)
+ [Services, capabilities and MCP: REST](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#rest)
+ [Controller APIs](https://github.com/caligrafy/caligrafy-quill/wiki/9.-Helpers-,-Forms-&-REST-API#restapi): the older way


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/The-JS-Client -->

The **JS client** is one ES module, with no dependency, that `php caligrafer.php client` writes from your capabilities:
one async function per capability (`create_book` becomes `createBook`), plus `call()`, `capabilities()`, `configure()`
and `CapabilityError`. Vue apps, the Vite SPA and Node scripts call the capabilities through it, with the session in a
page of the application and a token anywhere else. It talks to `Route::capabilities()`. Since 2.1.0.
## With Claude

```text
/caligrafy-quill:new-capability create_book books:write: add a book from the Bookshelf Vue app
```

Claude adds `Route::capabilities('/capabilities')` to `web.php`, runs `php caligrafer.php client` and calls `createBook`
from the app.

**Check** before you say OK:
+ every call of the app goes through a function of `capabilities.js`: no `axios`, `fetch` or `Authorization` header
  written by hand for capabilities;
+ `capabilities.js` was generated again after the last capability change.
## By hand

1. **The route.** In `application/config/routing/web.php`, before `Route::run();`:
    ```php
    Route::capabilities('/capabilities');   // GET lists, POST /capabilities/{name} calls: the JS client uses it
    ```
2. **Generate the client.**
    ```bash
    docker compose exec dev-box php caligrafer.php client public/js/capabilities.js
    ```
    ```text
     public/js/capabilities.js written: 17 capabilities, calls /capabilities (Route::capabilities('/capabilities') in web.php)
     import { createBook, CapabilityError } from './capabilities.js'
    ```
    For a Vite SPA, write it in `public/<app>/src/capabilities.js`. With another prefix:
    `php caligrafer.php client --prefix /api/capabilities` for `Route::capabilities('/api/capabilities')`.
3. **Use it in a Vue app.**
    ```js
    import { createBook, listBooks, CapabilityError } from './capabilities.js'

    try {
      const book = await createBook({ title: this.title, published_year: this.year, author_id: this.authorId })
      this.books = (await listBooks({ author_id: book.author_id })).data
    } catch (e) {
      if (e instanceof CapabilityError && e.code === 'invalid') this.errors = e.fields   // { published_year: '...' }
      else throw e
    }
    ```
    A Vue app loaded as a library imports it from the page:
    `this.api = await import(env.home + 'public/js/capabilities.js')`, then
    `this.api.configure({ baseUrl: env.home.replace(/\/$/, '') })`.
4. **From Node**, with a personal access token:
    ```js
    import { configure, listBooks } from './capabilities.mjs'

    configure({ baseUrl: 'http://localhost:8080', token: process.env.CALIGRAFY_TOKEN })
    const page = await listBooks({ page: 1 })
    ```
5. Run `client` again after you add or change a capability.
## <a name="api"></a>What the module exports

| Export | What it does |
| --- | --- |
| one function per capability, `createBook(input = {})` | calls it and returns its result (the `data` of the answer) |
| `call(name, input = {})` | calls any capability by name: `POST <prefix>/<name>` |
| `capabilities()` | what the caller may call, with the input schemas: `GET <prefix>` |
| `configure({ baseUrl, token, prefix, credentials })` | the application root (default: this origin), a personal access token, the prefix, the `fetch` credentials (default `same-origin`) |
| `CapabilityError` | thrown by a refused call: `status`, `code` (`invalid`, `forbidden`...), `message`, `fields` |

Each function carries a comment from the capability: its description, its flag (`read-only`, `destructive` or `writes`),
who may call it (`public`, the scope, or `signed in`) and its inputs, typed from the schema (`number`, `boolean` or
`string`; optional ones with `?`).

**In a page of the application** it uses the session: the cookie, and the CSRF token it reads once from `GET <prefix>`
and sends as `X-CSRF-Token` on every call that is not a `GET`. No key is ever in the bundle. **Elsewhere** (Node, another
origin) `configure({ token })` sends `Authorization: Bearer <token>` instead.

Left out of the module: [web-only capabilities](https://github.com/caligrafy/caligrafy-quill/wiki/Web-Only-Capabilities)
and Snap's own capabilities (`snap_*`).

Reference: [`Client::generate()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#client-generate),
[`Route::capabilities()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-capabilities).
## Common mistakes

+ **Forgetting `php caligrafer.php client` after a change**: the Vue app calls the old functions.
+ **A write over the session without `X-CSRF-Token`** (G54): 403. The client sends it; hand-written calls must too.
+ **A token or a key in a page or a Vue bundle**: browser code uses the session; tokens are for programs.
+ **The legacy API key in a client page** (G27, G50): while `LEGACY_API_KEY` is on, client pages get the key. Call
  capabilities with the JS client and set `LEGACY_API_KEY=false`.
## Related pages

+ [Vue: requests and capabilities](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.3-Requests#capabilities)
+ [REST API](https://github.com/caligrafy/caligrafy-quill/wiki/REST-API) · [Personal access tokens](https://github.com/caligrafy/caligrafy-quill/wiki/Personal-Access-Tokens)
+ [Caligrafer: `client`](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#client)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/MCP-for-AI-Agents -->

[MCP](https://modelcontextprotocol.io), the Model Context Protocol, is how AI agents such as Claude Code and Cursor use
tools. With `Route::mcp('/mcp')` every capability is a tool: its name, its description, its input schema, and hints that
say whether it only reads or destroys data. An agent sees only the tools its token allows, and its calls go through the
same checks, validation and audit as everyone else's. Since 2.1.0.
## With Claude

```text
/caligrafy-quill:new-capability list_books books:read read-only public: the catalog, for agents too
```

Claude adds `Route::mcp('/mcp')` to `web.php` when agents need it, creates a token with the scopes they need (shown once),
and checks `tools/list` and `tools/call`.

**Check** before you say OK:
+ `tools/list` with the agent's token lists the tools you expect, and not the ones its scopes do not allow;
+ an invalid `tools/call` answers `"isError": true` with a message per field.
## By hand

1. **The route.** In `application/config/routing/web.php`, before `Route::run();`:
    ```php
    Route::mcp('/mcp');   // AI agents: personal access tokens only
    ```
2. **A token.** `docker compose exec dev-box php caligrafer.php token create "Bookshelf agent" --scopes books:read,books:write`
   ([Personal access tokens](https://github.com/caligrafy/caligrafy-quill/wiki/Personal-Access-Tokens)).
3. **Connect Claude Code** over HTTP:
    ```bash
    claude mcp add --transport http bookshelf http://localhost:8080/mcp --header "Authorization: Bearer cq_..."
    ```
   or over stdio, the agent starting the server itself in the project folder:
    ```bash
    claude mcp add bookshelf -- docker compose exec -T dev-box php caligrafer.php mcp
    ```
4. **Try it as an agent does**, one JSON-RPC message per request:
    ```bash
    curl -s -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" \
         -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' http://localhost:8080/mcp
    curl -s -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" \
         -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"create_book","arguments":{"title":"Dune"}}}' \
         http://localhost:8080/mcp
    ```
    ```json
    {"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"{\"error\":{\"code\":\"invalid\",\"message\":\"Some of the inputs are invalid\",\"fields\":{\"published_year\":\"The Published Year field is required\",\"author_id\":\"The Author Id field is required\"}}}"}],"isError":true}}
    ```
## <a name="tools"></a>From capabilities to tools

`tools/list` gives one tool per capability the token may call (`Capabilities::available()`): public ones, and those whose
scope and level it passes. Web-only capabilities and those declared `mcp: false` are left out.

```json
{"name": "create_book", "title": "Create book", "description": "Adds a book to the Bookshelf catalog and returns it with its id and its author. The author must already exist: use list_authors to find author_id.",
 "inputSchema": {"type": "object", "properties": {
    "title": {"type": "string", "maxLength": 200, "description": "The title of the book"},
    "published_year": {"type": "integer", "minimum": 1450, "maximum": 2026, "description": "The year it was first published, for example 1969 (not after this year)"},
    "summary": {"type": "string", "maxLength": 2000, "description": "Optional: one or two sentences about the book"},
    "author_id": {"type": "integer", "description": "The id of its author (list_authors)"}},
  "additionalProperties": false, "required": ["title", "published_year", "author_id"]},
 "annotations": {"readOnlyHint": false, "destructiveHint": false, "openWorldHint": false}}
```

| Tool field | From |
| --- | --- |
| `name` | the capability's `name` |
| `title` | the name with spaces, capitalized (`create_book`: Create book) |
| `description` | the capability's `description`: write it for an agent, with what it returns and where to find the ids it needs |
| `inputSchema` | its `$rules` and `$descriptions` ([Capability inputs](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Inputs#schema)) |
| `readOnlyHint` | `readOnly` |
| `destructiveHint` | `destructive`, when it is not also read-only |
| `openWorldHint` | always `false` |

`initialize` answers the server's name (`APP_NAME`), the framework version and these instructions for the agent: "Tools
are the capabilities of this application that your token allows. Tools marked destructive delete or overwrite data:
confirm with the user first."

**Calls.** `tools/call` runs `Capabilities::call()` with the arguments. A success is `"isError": false`, the data as JSON
in `content[0].text` and the object in `structuredContent` (a list is given as `{"result": [...]}`). A refusal is a tool
result with `"isError": true` and the same error as REST, so the agent can read the reason and correct itself. A tool the
token cannot see, or one that does not exist, answers the JSON-RPC error `-32602` `Unknown tool: <name>`.

<a name="mcpfalse"></a>**`mcp: false`** keeps a capability out of the tools: one only a browser can use, such as a push
subscription. REST still reaches it.
## <a name="http"></a>Over HTTP: `Route::mcp`

+ `POST` only, one JSON-RPC 2.0 message per request (no batches), answered in JSON (no event stream): `initialize`,
  `ping`, `tools/list`, `tools/call`. A notification (no `id`) gets `202` and no body. `GET` and `DELETE` answer `405`.
+ Protocol versions `2025-11-25`, `2025-06-18`, `2025-03-26`, `2024-11-05`; any other request gets the first.
+ **Personal access tokens only**, never the session or the legacy key. Without a valid token: `401`,
  `WWW-Authenticate: Bearer error="invalid_token"` and `{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Unauthorized: send Authorization: Bearer <personal access token>"}}`.
+ A browser request from another site (an `Origin` header) is refused with `403 Origin not allowed`, against DNS
  rebinding. Allowed: no `Origin` (agents), the application's own host, and the origins of `MCP_ALLOWED_ORIGINS` in `.env`
  (comma separated, such as `MCP_ALLOWED_ORIGINS=https://inspector.example`).
+ A message that is not JSON, or not one JSON-RPC request, answers `400`.
## <a name="stdio"></a>Over stdio: `php caligrafer.php mcp`

One JSON-RPC message per line on standard input, one answer per line on standard output. Without a token it has full
access, like any command you run yourself, and says so on standard error:
`caligrafer mcp: no token, full local access (set CALIGRAFY_TOKEN to limit it)`. With `CALIGRAFY_TOKEN=cq_...` (or
`--token cq_...`) it has the rights of that token. For agents that reach the application over the network, use
`Route::mcp` and a token.

Reference: [`Route::mcp()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route-mcp),
[`Mcp\Server`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#mcp-server),
[`Mcp\Http`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#mcp-http).
## Common mistakes

+ **Sending the legacy key to MCP** (G56): 401. MCP takes tokens only.
+ **`webOnly: true` on a feature agents need** (G143): it is not a tool. Keep the work in a plain capability.
+ **`register_user` over MCP** (G81): refused; sign-up is the sign-up page.
+ **No page to create tokens online** (G79): agents cannot connect to a deployed application without one.
## Related pages

+ [Personal access tokens](https://github.com/caligrafy/caligrafy-quill/wiki/Personal-Access-Tokens) · [Scopes and access](https://github.com/caligrafy/caligrafy-quill/wiki/Capability-Scopes-and-Access)
+ [Read-only and destructive capabilities](https://github.com/caligrafy/caligrafy-quill/wiki/Read-Only-and-Destructive-Capabilities)
+ [Services, capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#mcp)
+ [Claude Code plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant -->

**Snap Cards** turn every capability of your app into a card a person can use, and **the assistant** answers what
they type, say or attach with those cards. One line of `web.php`, `Route::snap();`, gives every signed-in person a Home
that shows what needs them, and a conversation that keeps its context. Nothing to design: each card is built from what
your capability already declares (its rules, descriptions, `readOnly`, `destructive`), and shown the way your app
shows it: its card view in your app's own look, or a card designed in your design system ([how a card looks](#looks)). Since 2.23.0.

**Since 2.26.0** the assistant's free-text understanding with Claude needs `php caligrafer.php add snap` once (the Anthropic SDK); without it, with `ANTHROPIC_API_KEY` set, the assistant answers from the cards' names and logs which command to run.
## With Claude

```text
/caligrafy-quill:assistant
```

Claude adds `Route::snap();` to `web.php`, runs `php caligrafer.php snap install`, writes the hints of
`application/config/snap.php` for your capabilities (titles, columns, the numbers of Home with their actions, what
Home invites to browse), writes a card view for each main list and record from your own pages (so every card looks
like your app), adds the two scheduled jobs, and asks you for an Anthropic API key if you want the assistant
to understand free text.

**Check**

+ `php caligrafer.php snap` shows `[ok]` on every line you need.
+ Signed in, `/assistant` greets you; `/snap` shows one card per capability you may use.
+ `php caligrafer.php snap views` shows `[ok]` for each card view.
## <a name="start"></a>By hand, in three steps

**1. One line in `application/config/routing/web.php`** (after `Auth::authentication(...)`: the assistant is for
signed-in people):

```php
Route::snap();
```

**2. Its tables, and a starter hints file:**

```bash
php caligrafer.php snap install
```

It creates the `caligrafy_snap_*` tables (they also come with `php caligrafer.php platform install`, and with every
deploy) and `application/config/snap.php`, then prints what is ready:

```text
 Snap Cards and the assistant
  [ok] Tables            caligrafy_snap_*
  [ok] Route             Route::snap(); in application/config/routing/web.php
  [ok] Card hints        application/config/snap.php (optional: cards work without it)
  [--] Background tasks  the queue runs them: array('name' => 'queue', 'capability' => 'queue_work', ...)
  [--] Routines          array('name' => 'snap-routines', 'capability' => 'snap_routines_due', ...)
  [--] Assistant model   ANTHROPIC_API_KEY in .env (without it the assistant answers from the cards' names)
```

**3. Open `/assistant`.** That is all you need. The three lines marked `[--]` are optional:

+ **Background tasks**: a capability declared `#[Capability(..., async: true)]` runs in the queue (see
  [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs)): add the `queue_work` job to
  `application/config/schedule.php`.
+ **Routines** (things the assistant does for a person on a rhythm): add
  `array('name' => 'snap-routines', 'capability' => 'snap_routines_due', 'every' => '1m', 'timeout' => 50)`.
+ **The assistant's model**: `ANTHROPIC_API_KEY=` in `.env` (a key from console.anthropic.com, API keys). Without it,
  the assistant still answers the names of your cards ("the catalog", "lend a book"), your shortcuts and "What can I
  do?"; with it, Claude understands anything ("lend Kindred to Sam for a week", "who wrote it?").

`Route::snap(['assistant' => '/help', 'cards' => '/cards'])` puts them at other addresses.
## <a name="what"></a>What people get

| Address | What it is |
| --- | --- |
| `/assistant` | **Home**: what needs them now, the numbers that call for an action, things to browse, their shortcuts; and the **task space**: one answer at a time, with what to do next |
| `/assistant/noticed` | What the assistant noticed (only if they turned noticing on), and their routines |
| `/snap` | Every card they may use (a gallery); `/snap/c/<capability>` one card at its own address |

**Home** is an orchestrator: it decides what the person should concentrate on and puts it first.
+ The assistant says it in at most two lines: what needs them on a line of its own, then one nudge
  ("Since you looked at Kindred, you might like Parable of the Sower.").
+ Sections, in the order of what to do: **Needs you** (alerts, tasks waiting for an answer, changes to confirm),
  insights, **For you** (offers), **In progress**, things to browse, **Just done**, **Your shortcuts**.
+ Each kind of card has its own shape (the card grammar below), and every row is full.

**The task space** is a conversation:
+ The assistant's line sits on the page; the cards are white, and read as the rest of the sentence.
+ Suggestions say what to do next, never a dead end (*Back to Home*, *What else can I do?*).
+ It keeps the context: "it", "this one", "him" mean what is on screen; "delete it" works at once.
+ Back and forth, history, a rating, a different answer; the keyboard (⌥K / Alt+K to type, ⌥M / Alt+M to talk);
  the + attaches pictures, PDFs and text files for the assistant to read.
## <a name="cards"></a>The cards: five families, nine types

Every card names its family with its type. People never see these names; they are how you talk about the cards.

| Family | Type | What it does | Built from |
| --- | --- | --- | --- |
| **Ask** | Form | asks for the inputs still missing | the rules and descriptions of a capability |
| **Ask** | Choice | one pick (a book, an author) | a `*_id` input and the list it comes from |
| **Ask** | Confirm | what will change, before it changes | any capability that is not `readOnly` |
| **Show** | Answer | one record, a value, a message | the result of a read |
| **Show** | List | rows that open | a list result (with pages) |
| **Go** | Shortcut | a card a person saved, one click away | the person |
| **Track** | Task | work running in the background | `async: true` |
| **Offer** | Suggestion | the moment they usually do something; an alert | noticing; the hint `alert` |
| **Offer** | Routine | do it for them on a rhythm | noticing |

**A change only ever runs from its Confirm.** The Confirm carries a one-time token tied to the person, the capability
and these exact inputs; the assistant's model never sees it, and a card at an address never changes data. A change that
can be undone (an update, a creation, a hint `undo`) offers **Undo** right after.
## <a name="looks"></a>How a card looks: card views

A card that shows data (a list, a record) shows it the way your app does, at the size of a card (since 2.25.0):

1. **Its card view.** `application/views/snap/<capability>.pug` is a small Pug view made for the card, in your app's own
   markup and classes, rendered by the server inside the card. It keeps only what the card needs: a list's rows, a
   record's header and summary; the page around it (its title, tabs, filters, forms) stays on the page, and the card
   adds its own actions under it.

   ```pug
   //- snap card of list_books, from Bookshelf/books.pug 5fb9e0cf
   ul.cq-rows
       each $b in $rows
           li.cq-row
               .cq-row-main
                   p.cq-row-title
                       a(href="{$home}books/{$b['id']}", data-snap-open='get_book', data-snap-input=json_encode(array('id' => $b['id'])))= $b['title']
                   p.cq-row-meta= $b['author']['name'] . ', ' . $b['published_year']
   ```

   It gets `$rows` and `$page` (`page`, `pages`, `total`) for a list, `$record` for one record, `$result` (what the
   capability returned), `$input`, `$card`, `$home`, `$authorized` and `$user`. A link with `data-snap-open` and
   `data-snap-input` opens that card in the conversation. Its first line names the page it was made from and that
   page's fingerprint (`shasum application/views/Bookshelf/books.pug | cut -c1-8`): when the page changes,
   `php caligrafer.php snap views` and `doctor` say the card view is stale.

   **Claude writes them**: `/caligrafy-quill:assistant` reads each page and the scripts that draw it, keeps the part
   that matters and writes the card view with your classes only (a built stylesheet, such as Tailwind's, is checked
   class by class).
2. **The part of a page marked for it**, when there is no card view: `data-snap="<capability>"` on an element of the
   view whose first data it is shows that part alone, in a frame sized to it.
3. **A card designed for its data**, when there is neither, in your design system: the `--design-*` tokens of
   [`DESIGN_STYLE`](https://github.com/caligrafy/caligrafy-quill/wiki/Design-Styles), else Caligrafy's. A record becomes a
   hero (its name, a line under it, badges with a tone), a few numbers, its details, its text and its tags; a list
   becomes rows. With `ANTHROPIC_API_KEY`, Claude designs it from a sample of the data once per shape of data (kept 30
   days); without a key, rules do.

A card never shows a whole page. The hints decide otherwise:

```php
'search_books' => array('card' => 'snap/list_books'),   // the same rows as the catalog: its card view
'get_user' => array('card' => false),                     // no card view
'get_book' => array('view' => 'Bookshelf/book'),          // without a card view: this page, whole
'list_people' => array('design' => array('title' => 'name', 'subtitle' => 'role', 'meta' => array('email', 'active_cases'),
    'badge' => array('path' => 'status', 'tones' => array('away' => 'warning')))),   // a designed card, by hand
```

```text
php caligrafer.php snap views

 Card views (application/views/snap/<capability>.pug)
  [ok] get_book                   from Bookshelf/book.pug
  [ok] list_authors               made for the card (no page)
  [!!] list_books                 Bookshelf/books.pug changed since its card view was made: write it again
  [--] get_user                   no card view: a card designed from its data
```
## <a name="grammar"></a>Home's card grammar

Each section of Home uses one template, chosen by what the person does with it:

| Template | For | Width | Shows |
| --- | --- | --- | --- |
| banner | act now: alerts, waiting for an answer, failed, to confirm | full width, stacked | tinted by severity, a severity tag, its one action |
| offer | decide: suggestions, routines | halves | the question, why, Yes and Not now |
| progress | watch: tasks waiting or running | full-width rows | what it is doing now, its time, a live bar, a status |
| object | browse: the things your app is about | thirds (alone: a feature card) | why it is here, its name, two facts |
| update | revisit: just done | full-width rows | the result, how long ago, Done or Failed |
| shortcut | go | quarters | an icon and a name |
| insight | measure | a strip at the top | a number, and the action it calls for |

**The count rule**: a row has as many columns as cards (up to the template's most: offers 2, objects 3, shortcuts 4),
so no row has a hole; what does not fit is behind *See all*.
## <a name="hints"></a>Hints: `application/config/snap.php`

Cards work without hints. A hint makes one better: its name, the columns of a list, the words the assistant says,
the numbers of Home with their actions, what Home invites to browse, when an action applies.

```php
<?php
return array(
    'about' => 'a library app: the books of a catalog, their authors, and the books lent to people',
    'cards' => array(
        'list_books' => array(
            'title' => 'The catalog',
            'columns' => array('title', 'author.name', 'published_year'),
            'empty' => 'No book yet.',
            'insight' => array('label' => 'New this month', 'since' => array('field' => 'created_at', 'days' => 30),
                'action' => array('capability' => 'list_books', 'text' => 'Browse the catalog')),
            'discover' => array('open' => 'get_book', 'key' => 'id', 'title' => 'title', 'meta' => array('author.name', 'published_year'),
                'new' => 'created_at', 'related' => 'author.id', 'opened' => array('get_book' => 'id'),
                'unavailable' => array('capability' => 'list_loans', 'field' => 'book_id'), 'available_label' => 'On the shelf',
                'title_section' => 'On the shelf for you'),
        ),
        'lend_book' => array('done' => 'Done! {heading} is lent. Enjoy the read.',
            'applies' => array('not_in' => array('capability' => 'list_loans', 'field' => 'book_id'))),
        'return_book' => array('applies' => array('in' => array('capability' => 'list_loans', 'field' => 'book_id'))),
        'reading_report' => array('working' => array('Counting the books of each author…', 'Putting the report together…')),
    ),
);
```

| Key | What it does |
| --- | --- |
| `title`, `lead`, `submit`, `icon` | the card's name, its line, its button, its icon (Lucide names) |
| `columns`, `labels`, `hide`, `noun`, `variant` | a list's columns, the labels of fields, fields left out, what its rows are ("authors") |
| `values`, `choices` | the labels of fixed values; where a `*_id` field's choices come from |
| `open` | which capability a list's row opens (`array('capability' => 'get_book', 'input' => 'id', 'from' => 'book_id')`) |
| `full` | the page that shows the same thing in full (`'/books/{id}'`) |
| `empty`, `empty_next` | what an empty list says; what would fill it (`array('lend_book')`) |
| `done`, `consequence`, `confirm` | the assistant's line once done (`{heading}`), the line under a Confirm, its question |
| `undo` | what undoes it (`array('capability' => 'return_book', 'map' => array('book_id' => 'book_id'))`) |
| `next` | what it leads to (suggestions after it) |
| `applies` | when an action can be done to a record (`in` or `not_in` a list) |
| `alert` | an alert on Home when rows carry a flag (`'when' => 'overdue'`), with its action and tag |
| `insight` | a number on Home, only with the action it calls for |
| `discover` | the things Home invites to browse: more like what the person looked at, new, available by your rule |
| `working`, `async` | what a background task says while it runs; async without the attribute |
| `card` | its card view (`'snap/list_books'`, under `application/views`), or `false` ([how a card looks](#looks)) |
| `view` | without a card view, the page whose `data-snap` part shows it (`'Bookshelf/book'`: that page, whole), or `false` |
| `design` | how its data is shown without a page: `title`, `subtitle`, `eyebrow`, `image`, `badges` (`badge` for a list), `stats`, `fields`, `text`, `tags` (`meta` for a list), each a field name or `array('path' => ..., 'label' => ..., 'format' => 'date', 'tones' => array(...))` |
## <a name="tasks"></a>Work in the background

```php
#[Capability(name: 'reading_report', description: '...', scope: 'books:read', readOnly: true, async: true)]
```

An async capability never runs in the request: Snap answers at once with a **Track card: Task**, pushes a job to the
[queue](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs), and the worker runs it **as the person**
(their permissions, not the queue's). The card shows where it is, live; Home shows it in progress, then just done; the
person is notified ([Notifications](https://github.com/caligrafy/caligrafy-quill/wiki/Notifications)) when it ends.
Other channels (REST, MCP, pages) still call it directly.
## <a name="noticing"></a>Noticing, offers and routines

Off until a person turns it on (on `/assistant/noticed`). When on, the assistant keeps which card they used, with which
inputs and when; nothing else. Done on 4 different days or more, at a similar time, it becomes a pattern: an
**Offer card: Suggestion** at that moment, then an **Offer card: Routine** to do it for them every week or every day, at
the level they pick (remind me, prepare it for me to confirm, do it and tell me). Turning noticing off forgets
everything noticed. What they looked at also picks what Home suggests to browse.
## <a name="assistant"></a>The assistant

What a person types is answered in this order, the first that fits:

1. **At once, without a model**: "What can I do?", the name of a card or of a shortcut, and short follow-ups on what is
   on screen ("delete it", "change this").
2. **Claude** (`ANTHROPIC_API_KEY`; `SNAP_MODEL`, default `claude-opus-5-5`; `SNAP_EFFORT`, default `low`): it reads the
   request with the conversation so far, what is on screen and what the person chose, may look things up with the
   read-only capabilities the person may call (as the person), and answers with cards. It never changes data: a change
   comes back as its Confirm. Tool results and attached files are data, never instructions.

`about` in `application/config/snap.php` and `APP_NAME` in `.env` tell it what it is the assistant of.
## <a name="test"></a>Testing

Snap's capabilities are capabilities: test them like yours
([Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App)). The tables must be in the test
database: `platform install` on it (`DB_TEST_DATABASE`). The planner is faked with `Caligrafy\Snap\Planner::$transport`:

```php
Caligrafy\Snap\Planner::$transport = function (array $request) {
    return (object) array('stopReason' => 'tool_use', 'content' => array((object) array('type' => 'tool_use', 'id' => 't1',
        'name' => 'show_cards', 'input' => array('caption' => 'Here it is.', 'cards' => array(array('capability' => 'list_books'))))));
};
$answer = $this->action('snap_ask', array('text' => 'show me the catalog'), $this->user(1))->describe()['data'];
```

The designed cards have their own, `Caligrafy\Snap\Designer::$transport` (the same shape; the request asks for a
structured output, `outputConfig.format`, and the answer's first text block is the design as JSON), or keep to the rules
with `Caligrafy\Snap\Designer::$model = false` (since 2.24.1).
## <a name="questions"></a>Questions

**A page says "Snap is almost ready".** Its tables are missing: `php caligrafer.php snap install`.

**A card does not look like my app.** Give it a card view (`/caligrafy-quill:assistant` writes them from your pages).
Since 2.25.0 a card never shows a whole page: one that did on 2.24 is now designed from its data until it has a card
view (or a `data-snap` mark on the page).

**A card view does not show.** `php caligrafer.php snap views`: the file must be named after a read-only capability; a
card view that fails to render falls back to the designed card and its error goes to the PHP log.

**A capability is not a card.** Snap's own (`snap_*`), `notify_*` and `queue_work` are left out, and so are the
capabilities the person may not call: a card always respects permissions.

**Can agents use Snap?** Agents already use your capabilities over MCP; the `snap_*` capabilities serve a person's
shell: they are not MCP tools, nor functions of the generated JS client. `snap_card` and `snap_catalog` are capabilities, though: a program can ask for the card of
any capability.


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Ask-Cards -->

The **Ask** cards are the cards of [Snap](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant)
that ask a person for something before anything runs: **Ask: Form** asks for the inputs still missing, **Ask: Choice**
asks for one pick, and **Ask: Confirm** shows what a change will do and waits for the person's click. Nothing to design:
each is built from what the capability already declares (its `$rules`, `$descriptions`, `readOnly`, `destructive`).
Since 2.23.0.
## With Claude

```text
/caligrafy-quill:assistant
```

Claude adds `Route::snap();`, runs `php caligrafer.php snap install` and writes the hints of
`application/config/snap.php` for your capabilities: the titles, the labels of fields, where a `*_id` field's choices
come from, the line under a Confirm.

**Check**

+ Signed in, `/snap/c/create_book` shows the form of `create_book`, with a pick list for `author_id`.
+ Sending it shows a Confirm first; nothing is added until you click it.
## By hand

Ask cards need nothing but `Route::snap();` in `web.php` (after `Auth::authentication(...)`) and the Snap tables
(`php caligrafer.php snap install`): every capability the person may call gets its card. Take the capability of
[Build once](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#service):

```php
#[Capability(name: 'create_book', description: 'Adds a book', scope: 'books:write')]
class CreateBook extends Service {
    public $rules = ['title' => 'required|max_len,255', 'author_id' => 'required|integer'];
    public $filters = ['title' => 'trim|sanitize_string'];
    public $descriptions = ['title' => 'The title of the book'];
    public function handle(array $input, Context $context) {
        return (new Book('books'))->create($input);
    }
}
```

1. **Ask: Form.** Open `/snap/c/create_book`. The card has a field per input of `$rules` (the input `page` is left
   out); its limits come from the rules (`max_len,255` is a maximum length), its help line from
   `$descriptions`, its button from the capability's verb ("Add").
2. **Ask: Choice.** `author_id` is a `<thing>_id`, and `list_authors` is a read-only capability the person may call: the
   field becomes a pick among the authors. Open `/snap/c/create_book?in={"title":"Kindred"}`: with the title known, one
   pick is all that is missing, so the card is an **Ask: Choice** ("Which author?"), with what was already said shown
   read-only above it.
3. **Ask: Confirm.** Send the card. `create_book` is not `readOnly`, so it does not run: Snap answers with its Confirm
   (what will change, its question, its button "Yes, add"), and only the person's click runs it. A change that can be
   undone then offers **Undo**.
## <a name="form"></a>Reference: what builds an Ask card

`Caligrafy\Snap\Cards::ask()` builds the card ([API](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Cards#snap-cards-ask)),
`Cards::fields()` its fields ([API](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Cards#snap-cards-fields)):

| A field gets | From |
|---|---|
| its label | the hint `labels`, else the input's name in words, without `_id` (`published_year`: "Published year", `author_id`: "Author"); the `id` of `get_`, `update_` or `delete_<thing>` is named after the thing |
| its help line | `$descriptions` (a help line that starts with "The id of" is dropped when the field is a pick: a person picks by name) |
| required or not | the capability's schema (`required` in its rules) |
| its limits | the schema: `min`, `max`, `minlength`, `maxlength` |
| a select | the hint `values` (`array(1 => 'Monday', ...)`), or an `enum` in the schema |
| a pick (`choice`) | the first of: the hint `choices`, an `exists,<table>.<column>` rule (`list_<table>`), a `<thing>_id` input (`list_<things>`), the `id` of `get_`/`update_`/`delete_<thing>` (`list_<things>`); only a read-only capability the person may call, with 50 options at most (`Cards::MAX_OPTIONS`) |
| its icon | the hint `icons`, else a few known field names, else a dot |
| its current value | an `update_<thing>` form starts from the record of `get_<thing>` with the same `id` (the hint `current` names another reader) |

The options of a pick are the rows of its list: the value is `id` and the label the row's `title`, `name` or
`username`; `'choices' => array('author_id' => array('capability' => 'list_authors', 'value' => 'id', 'label' => 'name'))`
says otherwise.

A card is an **Ask: Choice** when exactly one required input is missing, it is a pick, and there are no errors to show;
anything else is an **Ask: Form**. `Cards::needsInput()` decides whether an Ask card still needs the person: a required
input is missing, or only the id of a thing to change was given (an `update_` starts as its form); a delete needs
nothing more than its id.
## <a name="confirm"></a>Reference: Ask: Confirm and consent

**A change only ever runs from its Confirm.** `Caligrafy\Snap\Flow::next()` decides the next card of any capability,
whoever asks (a card that is sent, the assistant's fast path, the model's choice):

```text
read:          inputs missing -> its Ask card; complete -> runs -> Show card
write/destroy: inputs missing -> its Ask card; refused by its rules -> Ask with errors; else -> Ask: Confirm
```

`Caligrafy\Snap\Consent` ([API](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-consent)) makes the
Confirm:

+ what will change (before and after), and a one-time token bound to this person, this capability and these exact
  inputs, for 10 minutes (`Consent::TTL`), kept in the session, never in the card's address. Only the person's click on
  that card sends it back: a model, a page or a link cannot make one.
+ a confirmed change is recorded in the [audit log](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#audit)
  (capability `snap_confirm`).
+ what undoes it: what was true before (an `update_`), what was created (`create_` is undone by `delete_`), or the hint
  `undo`. Undoing is a change too: it gets its own Confirm.

The Confirm's words: its question is the hint `confirm`, else "<title>: <subject>?"; the line under it is the hint
`consequence`, else *This cannot be undone.* for a `destructive` capability, *You can undo it right after.* when it can
be undone, *This cannot be undone from here.* otherwise. Its button is the hint `submit` (or the verb), as
"Yes, <verb>" (a delete names what it deletes).
## Common mistakes

+ **A pick shows as a text field.** Its list must be a read-only capability the person may call, named `list_<things>`
  (or given by the hint `choices`), with 50 rows at most.
+ **Hints on the capability.** Titles, labels, `choices`, `confirm` are keys of `application/config/snap.php`, keyed by
  capability name; a key the framework does not know is ignored silently (G157).
+ **A capability is not a card.** Snap's own (`snap_*`), `notify_*`, `queue_work` and web-only capabilities are left
  out, and so are the capabilities the person may not call.
## Related pages

+ [Snap Cards and the assistant](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant): the overview
+ [Snap: Show cards](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Show-Cards)
+ [Snap: hints](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Hints)
+ [Validation rules](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation): the rules a form is built from
+ [API: Snap](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap) · [API: Snap\Cards](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Cards)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Show-Cards -->

The **Show** cards of [Snap](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant) show
what a read returned: **Show: List** for rows (with their pages), that open one by one, and **Show: Answer** for one
record, a value or a message. A read-only capability whose inputs are complete runs at once and answers with its Show
card. Since 2.23.0; how they look (card views, designed cards) since 2.24.0 and 2.25.0.
## With Claude

```text
/caligrafy-quill:assistant
```

Claude writes the hints of the lists (`title`, `columns`, `empty`, `open`) and a card view for each main list and
record from your own pages, so the cards look like your app.

**Check**

+ `/snap/c/list_books` shows the catalog as rows; a row opens its book.
+ `php caligrafer.php snap views` shows `[ok]` for each card view.
## By hand

With `Route::snap();` in `web.php` and the Snap tables, every read-only capability the person may call is a Show card
as soon as its inputs are complete:

1. **Show: List.** `list_books` returns a list (or a page of
   [`paginate()`](https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Pagination)): `/snap/c/list_books` is a
   Show: List. Its rows open `get_book` because the name says so (`list_books` and `search_books` open
   `get_book` with the row's `id`, when the person may call it).
2. **Show: Answer.** `get_book` returns one record: `/snap/c/get_book?in={"id":3}` is a Show: Answer, a record named
   by its own name, with the actions of the same thing the person may call (`update_book` as *Change*, `delete_book` as
   *Delete*, and other `<verb>_book` capabilities such as `lend_book`), each an Ask card.
3. **Better words and columns.** In `application/config/snap.php`:
    ```php
    <?php
    return array(
        'cards' => array(
            'list_books' => array(
                'title' => 'The catalog',
                'columns' => array('title', 'author.name', 'published_year'),
                'empty' => 'No book yet.',
            ),
        ),
    );
    ```
## <a name="list"></a>Reference: Show: List

`Caligrafy\Snap\Cards::show()` builds both ([API](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Cards#snap-cards-show)).
A result that is a list (or a page: `data`, `total`, `pages`) is a List:

| The card's | Comes from |
|---|---|
| title | the hint `title`, else the capability's name in words |
| columns | the hint `columns` (a related row's field is named after the relation: `author.name` is "Author"), else the first row's fields, without `id`, `*_id`, passwords, `created_at`, `updated_at` and long texts (over 140 characters), a related row by its `name` or `title`; 5 at most |
| what a row opens | the hint `open` (`array('capability' => 'get_book', 'input' => 'id', 'from' => 'book_id')`), else `get_<thing>` for `list_<things>` and `search_<things>` |
| its count line | the total and the hint `noun` ("authors"), else a noun from the name |
| an empty list | the hint `empty`, else *Nothing here yet.*; the hint `empty_next` names what would fill it |
| pages | `page`, `pages`, `total` of a `paginate()` page |
| its look | `variant` (`rows` by default), then its card view, else the part of its page marked for it, else rows designed for its data ([card views](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Card-Views)) |
## <a name="answer"></a>Reference: Show: Answer

| The result | The card |
|---|---|
| one record (an array) | variant `record`: its heading is the record's own title or name, else the title or name of the record it is about (a loan is about its book), else its username, else `#id` (`Cards::name()`); its fields; its actions; its card view or designed blocks |
| a value | variant `fact`: the value; `true` and `false` read *Yes* and *No*; nothing reads *Done* |

**The actions of a record** are the capabilities of the same thing the person may call: `update_<thing>` (*Change*),
`delete_<thing>` (*Delete*), and any other `<verb>_<thing>` (it gets `<thing>_id`). The hint `applies` keeps only what
can be done now:

```php
'lend_book' => array('applies' => array('not_in' => array('capability' => 'list_loans', 'field' => 'book_id'))),
'return_book' => array('applies' => array('in' => array('capability' => 'list_loans', 'field' => 'book_id'))),
```

The list is read as the person, once per request; a list they may not read leaves the action out
([`Cards::applies()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Cards#snap-cards-applies)).

**A refusal that is not about the inputs** (not found, conflict, forbidden) is a notice instead of a result
([`Cards::notice()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Cards#snap-cards-notice)); a refusal about
the inputs comes back as the Ask card with its errors.
## Common mistakes

+ **A row does not open.** The getter must be named `get_<thing>` for `list_<things>`, and the person must be allowed
  to call it; or give the hint `open`.
+ **A card shows a whole page** on 2.24. Since 2.25.0 a card never does: it shows its card view, else the part of a page
  marked `data-snap`, else a card designed from its data (G163).
+ **`select()` with models** fills the other columns with `null`, and the card shows them: add `arrays()` (G138).
## Related pages

+ [Snap Cards and the assistant](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant)
+ [Snap: card views](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Card-Views): how a Show card looks
+ [Snap: Ask cards](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Ask-Cards)
+ [Snap: hints](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Hints)
+ [API: Snap\Cards](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Cards)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Go-and-Track-Cards -->

Two families of [Snap](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant) cards belong
to a person rather than to a capability: **Go: Shortcut**, a card they saved (a capability with its inputs) run with
one click, and **Track: Task**, work that runs in the background for them and shows where it is. Since 2.23.0.
## With Claude

```text
/caligrafy-quill:assistant
```

Claude marks the slow capabilities `async: true`, writes their `working` lines in `application/config/snap.php` and
adds the `queue_work` job to `application/config/schedule.php`. Shortcuts need nothing: people save their own.

**Check**

+ `php caligrafer.php snap` shows `[ok] Background tasks`.
+ On `/assistant`, *Save* on a card adds it under **Your shortcuts**; typing its title runs it.
+ An async card answers at once with a Task card that moves from *Waiting to start* to *Done*.
## <a name="shortcut"></a>Go: Shortcut

A person saves a card from its *Save* control (the capability `snap_shortcut_save`: a `title` of up to 80 characters,
the `capability` and its `inputs`). Their shortcuts are on Home, under **Your shortcuts**, and typing a shortcut's title
in the assistant runs it at once, without a model.

+ **Running one goes through `Snap\Flow` like any card**: a read shows its result, a change asks for its Confirm. A
  shortcut never skips consent.
+ **Only to a capability the person may use**: saving one to another is refused.
+ **12 per person** (`Shortcuts::MAX`): a 13th answers *You have 12 shortcuts already: delete one first.*
+ A Show card says whether it is one of the person's shortcuts already, so its control reads *Save* or *Remove*.
+ The menu ("What can I do?") is a Go: Shortcut too, in its `menu` variant: the ready-made starts the app offers, not the
  ones a person saved.

They are kept in `caligrafy_snap_shortcuts` ([API: Snap\Shortcuts](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-shortcuts)).
## <a name="task"></a>Track: Task

A capability declared `async: true` never runs in the request when a Snap card starts it:

```php
#[Capability(name: 'reading_report', description: '...', scope: 'books:read', readOnly: true, async: true)]
```

The hint `'async' => true` in `application/config/snap.php` does the same without the attribute. Then:

1. **A read** starts as a task at once; **a change** after its Ask: Confirm.
2. The task is a row of `caligrafy_snap_tasks` and a job of the [queue](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs)
   (`snap_task_run`).
3. The worker runs the capability **as the person who asked** (their user, the web channel: their permissions, not the
   queue's full access), keeps the card it ends with, and notifies them
   ([Notifications](https://github.com/caligrafy/caligrafy-quill/wiki/Notifications)).

| Status | The card says | Then |
|---|---|---|
| `queued` | *Waiting to start* | |
| `running` | *Working on it* (and the hint `working` lines, in turn) | |
| `done` | *Done* | the Show card of the result |
| `needs_input` | *Needs your answer* | the Ask card of what the capability refused: the person answers it, a new task starts |
| `failed` | *Could not finish* | a notice, after the queue's retries |

Home shows tasks under **In progress**, then **Just done**; the ones that wait for an answer or failed are under
**Needs you**.

```php
'reading_report' => array('working' => array('Counting the books of each author…', 'Putting the report together…')),
```

**The queue must run.** Add the job to `application/config/schedule.php` (see
[Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs)), or run
`php caligrafer.php queue work`; without it, tasks stay *Waiting to start*.
## Common mistakes

+ **`async: true` only changes Snap** (G155). REST, MCP, `Route::page`, `Route::form`, `$this->call()` and
  `php caligrafer.php call` still run the capability in the request.
+ **Tasks never start**: the queue does not run (G155).
+ **A shortcut to a change runs it at once**: it does not. It asks for its Confirm, every time.
## Related pages

+ [Snap Cards and the assistant](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant#tasks)
+ [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs)
+ [Snap: Offer cards](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Offer-Cards): routines run as tasks
+ [API: Snap\Tasks](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-tasks) · [Snap\Shortcuts](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-shortcuts)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Offer-Cards -->

The **Offer** cards of [Snap](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant) are the
assistant's own suggestions. **Offer: Suggestion** comes at the moment a person usually does something, or when rows need
them (an alert). **Offer: Routine** offers to do it for them on that
rhythm. Both come from **noticing**, which is off until each person turns it on. Since 2.23.0.
## With Claude

```text
/caligrafy-quill:assistant
```

Claude adds the routines' job to `application/config/schedule.php` and writes the `alert` hints of the lists whose rows
carry a flag (an overdue loan).

**Check**

+ `php caligrafer.php snap` shows `[ok] Routines`.
+ On `/assistant/noticed`, turning noticing on and off works, and off forgets what was noticed.
## By hand

1. **The routines' job**, in `application/config/schedule.php` (see
   [Scheduled jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs)):
    ```php
    array('name' => 'snap-routines', 'capability' => 'snap_routines_due', 'every' => '1m', 'timeout' => 50)
    ```
   Routines at the *auto* level run as [tasks](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Go-and-Track-Cards#task),
   so the queue must run too.
2. **An alert**, for rows that need someone now, in `application/config/snap.php`:
    ```php
    'list_loans' => array('alert' => array('when' => 'overdue', 'message' => '{count} loan{s} overdue', 'label' => 'borrower')),
    ```
   When rows of `list_loans` (a read-only capability) have a true `overdue`, Home shows an Offer: Suggestion in its
   `alert` variant under **Needs you**; `'action' => '<capability>'` adds the button that takes care of it.
3. **People turn noticing on** at `/assistant/noticed`. Nothing is noticed before.
## <a name="noticing"></a>Reference: noticing

`Caligrafy\Snap\Offers` ([API](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-offers)):

+ **Opt-in per person**, off by default. When on, the assistant keeps which card they used, with which inputs and when
  (a read that ran, a change they confirmed, a task they started); nothing else. `/assistant/noticed` shows every
  pattern, each deletable; turning noticing off deletes everything noticed.
+ **A pattern** is the same request (capability and inputs) in the last 42 days (`WINDOW_DAYS`):
  + **weekly**: on 3 days or more (`MIN_DAYS`) of the same weekday, around the same hour ("You did this 3 Mondays in a
    row, around 9 am.");
  + **daily**: on 4 different days or more, around the same hour ("You did this on 4 different days, around 9 am.").

  Anything weaker says nothing.
+ **At most 2 offers at a time** (`MAX_OFFERS`): routines that are due, then suggestions of this moment, then routines
  to propose; never one dismissed. Each says why, and has *Not now* (today) and *Don't suggest this again* (never).
+ What a person opened also picks what Home suggests to browse (the hint `discover`).
## <a name="routine"></a>Reference: routines

Accepting an Offer: Routine is itself a change, with its Ask: Confirm (`snap_routine_save`), recorded in the audit log.
The person picks a level:

| Level | At the moment of the routine |
|---|---|
| `suggest` | an Offer: Suggestion |
| `confirm` | its Ask: Confirm, ready, under **Needs you** |
| `auto` | it runs as a task of its owner (the job `snap_routines_due`), and they are told |

A delete is never done on a rhythm: *A delete is never done on a rhythm.* A routine is stopped with
`snap_routine_delete`, from `/assistant/noticed`.
## <a name="alert"></a>Reference: alerts

The hint `alert` on a read-only capability whose rows carry a flag:

| Key | What it does |
|---|---|
| `when` | the field of a row that makes it count (true, not empty) |
| `message` | the line; `{count}` is how many rows, `{s}` an `s` when more than one |
| `title`, `reason` | the card's title and why (`{count}` works there too) |
| `label` | the field each row is named by (`title` by default); 5 are listed |
| `action`, `yes` | the capability that takes care of it and its button (*Take care of it*); without it, or when the person may not call it, the alert opens the list (*See them*) |
| `tag`, `severity` | *Needs you* and `danger` by default |
## Common mistakes

+ **No offer ever comes.** Noticing is off until the person turns it on; a pattern needs 3 weekdays or 4 days around one
  hour.
+ **Routines at the auto level never run.** The `snap-routines` job is missing from `schedule.php`, or the queue does
  not run.
+ **Hints on the capability.** `alert` is a key of `application/config/snap.php`, not of `#[Capability]` (G157).
## Related pages

+ [Snap Cards and the assistant](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant#noticing)
+ [Snap: Go and Track cards](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Go-and-Track-Cards)
+ [Snap: hints](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Hints)
+ [Scheduled jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs)
+ [API: Snap\Offers](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-offers)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Card-Views -->

A **card view** makes a [Snap](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant) card
that shows data (a list, a record) look like your app: `application/views/snap/<capability>.pug` is a small Pug view,
in your own markup and classes, that the server renders inside the card. Without one, the card shows the part of a page
marked for it, or a card designed for its data in your design system. A card never shows a whole page. Since 2.25.0
(the `data-snap` mark and designed cards since 2.24.0).
## With Claude

```text
/caligrafy-quill:assistant
```

Claude reads each page and the scripts that draw it, keeps the part that matters (a list's rows, a record's header and
summary) and writes the card view with your classes only (a built stylesheet, such as Tailwind's, is checked class by
class).

**Check**

+ `php caligrafer.php snap views` shows `[ok]` for each card view.
+ `/snap/c/list_books` shows the rows as the catalog page does, without its title, tabs and filters.
## By hand

1. **Write the card view.** It is named after a read-only capability: `application/views/snap/list_books.pug`. Its
   first line names the page it was made from and that page's fingerprint
   (`shasum application/views/Bookshelf/books.pug | cut -c1-8`):
    ```pug
    //- snap card of list_books, from Bookshelf/books.pug 5fb9e0cf
    ul.cq-rows
        each $b in $rows
            li.cq-row
                .cq-row-main
                    p.cq-row-title
                        a(href="{$home}books/{$b['id']}", data-snap-open='get_book', data-snap-input=json_encode(array('id' => $b['id'])))= $b['title']
                    p.cq-row-meta= $b['author']['name'] . ', ' . $b['published_year']
    ```
   Pug in Caligrafy is PHP: strings join with `.`, never `+`.
2. **Check it.**
    ```bash
    php caligrafer.php snap views
    ```
    ```text
     Card views (application/views/snap/<capability>.pug)
      [ok] get_book                   from Bookshelf/book.pug
      [ok] list_authors               made for the card (no page)
      [!!] list_books                 Bookshelf/books.pug changed since its card view was made: write it again
      [--] get_user                   no card view: a card designed from its data
    ```
   `snap views` exits 1 when a card view is stale; `php caligrafer.php doctor` warns too (*Snap card views*).
## <a name="variables"></a>Reference: what a card view gets

| Variable | What it is |
|---|---|
| `$rows`, `$page` | for a list: its rows, and `page`, `pages`, `total` of a `paginate()` page |
| `$record` | for one record |
| `$result` | what the capability returned, pages included, as plain arrays |
| `$input` | the card's inputs |
| `$card` | the card: its `capability` and `title` |
| `$home`, `$authorized`, `$user` | the address of the application (ending with `/`), whether someone is signed in, who |

A link with `data-snap-open="<capability>"` and `data-snap-input='{"id":7}'` opens that card in the conversation
instead of leaving it. A card view is inserted as HTML: its `<script>` tags do not run (G163).
## <a name="order"></a>Reference: how a Show card looks, best first

`Caligrafy\Snap\Views` ([API](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-views)) decides:

1. **Its card view**: `application/views/snap/<capability>.pug`, or the view the hint `card` names
   (`'card' => 'snap/list_books'`, under `application/views`); `'card' => false` for none. One that fails to render
   falls back to the designed card, and its error goes to the PHP log.
2. **The part of its page marked for it**: on the view of a `Route::page` whose first data is this capability, the
   element with `data-snap="<capability>"` is shown alone, in a frame sized to it. A whole page only when the hint
   `view` names it (`'view' => 'Bookshelf/book'`); `'view' => false` for none.
3. **A card designed for its data** (`Caligrafy\Snap\Designer`), in your design system: the `--design-*` tokens of
   [`DESIGN_STYLE`](https://github.com/caligrafy/caligrafy-quill/wiki/Design-Styles), else Caligrafy's. A record becomes
   a hero (its name, a line under it, badges with a tone), a few numbers, its details, its text and its tags; a list
   becomes rows. Who designs it: the hint `design` when you give one; else Claude, with `ANTHROPIC_API_KEY`, from a
   sample of the data, once per shape of data (kept 30 days in the cache); else rules from the names of the fields.

```php
'search_books' => array('card' => 'snap/list_books'),   // the same rows as the catalog: its card view
'get_user' => array('card' => false),                     // no card view
'get_book' => array('view' => 'Bookshelf/book'),          // without a card view: this page, whole
'list_people' => array('design' => array('title' => 'name', 'subtitle' => 'role', 'meta' => array('email', 'active_cases'),
    'badge' => array('path' => 'status', 'tones' => array('away' => 'warning')))),   // a designed card, by hand
```

The `design` hint: `title`, `subtitle`, `eyebrow`, `image`, `badges` (`badge` for a list), `stats`, `fields`, `text`,
`tags` (`meta` for a list), each a field name or `array('path' => ..., 'label' => ..., 'format' => ..., 'tones' => array(...))`.
Formats: `text`, `number`, `money`, `percent`, `date`, `datetime`, `bool`, `email`, `url`; tones: `success`, `warning`,
`danger`, `info`, `neutral` (`Designer::FORMATS`, `Designer::TONES`).
## Common mistakes

+ **A card view does not show.** It must be named after a read-only capability; run `php caligrafer.php snap views`.
+ **A card looked like a whole page on 2.24, and designed since 2.25.0.** Give it a card view, or mark the part with
  `data-snap` (G163).
+ **A class of a built stylesheet does nothing.** With Tailwind, a card view can only use classes the build already has.
+ **`+` between strings** in Pug: Caligrafy renders Pug with PHP; join with `.`.
## Related pages

+ [Snap Cards and the assistant](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant#looks)
+ [Snap: Show cards](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Show-Cards)
+ [Views and page components](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views)
+ [Design styles](https://github.com/caligrafy/caligrafy-quill/wiki/Design-Styles)
+ [Caligrafer: `snap`](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#snap)
+ [API: Snap\Views and Snap\Designer](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-views)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Hints -->

**Hints** make a [Snap](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant) card better:
its name, the columns of a list, the words the assistant says, the numbers of Home with their actions, what Home
invites to browse, when an action applies. Cards work without any: each is built from what its capability declares.
The hints live in one file the app owns, `application/config/snap.php`, keyed by capability name. Since 2.23.0.
## With Claude

```text
/caligrafy-quill:assistant
```

Claude writes `application/config/snap.php` for your capabilities: `about`, titles, columns, the numbers of Home with
their actions, what Home invites to browse, the card views.

**Check**

+ `php caligrafer.php snap` shows `[ok] Card hints`.
+ Each key you see in the file is in the table below: a key the framework does not know is ignored silently.
## By hand

`php caligrafer.php snap install` writes a starter file when there is none. A complete one:

```php
<?php
return array(
    'about' => 'a library app: the books of a catalog, their authors, and the books lent to people',
    'cards' => array(
        'list_books' => array(
            'title' => 'The catalog',
            'columns' => array('title', 'author.name', 'published_year'),
            'empty' => 'No book yet.',
            'insight' => array('label' => 'New this month', 'since' => array('field' => 'created_at', 'days' => 30),
                'action' => array('capability' => 'list_books', 'text' => 'Browse the catalog')),
            'discover' => array('open' => 'get_book', 'key' => 'id', 'title' => 'title', 'meta' => array('author.name', 'published_year'),
                'new' => 'created_at', 'related' => 'author.id', 'opened' => array('get_book' => 'id'),
                'unavailable' => array('capability' => 'list_loans', 'field' => 'book_id'), 'available_label' => 'On the shelf',
                'title_section' => 'On the shelf for you'),
        ),
        'lend_book' => array('done' => 'Done! {heading} is lent. Enjoy the read.',
            'applies' => array('not_in' => array('capability' => 'list_loans', 'field' => 'book_id'))),
        'return_book' => array('applies' => array('in' => array('capability' => 'list_loans', 'field' => 'book_id'))),
        'reading_report' => array('working' => array('Counting the books of each author…', 'Putting the report together…')),
    ),
);
```

A file that returns the cards alone (no `'cards'` key) works too. `about` (and `APP_NAME` in `.env`) tells the
assistant what it is the assistant of.
## <a name="keys"></a>Reference: every key of a card

| Key | What it does | Page |
|---|---|---|
| `title`, `lead`, `submit`, `icon` | the card's name, its line, its button, its icon (Lucide names) | [Ask](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Ask-Cards) |
| `labels`, `icons`, `hide` | the labels and icons of fields, the fields left out | [Ask](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Ask-Cards) |
| `values` | the labels of fixed values: `array('weekday' => array(1 => 'Monday', ...))` makes a select | [Ask](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Ask-Cards) |
| `choices` | where a field's choices come from: `array('author_id' => 'list_authors')`, or `array('capability' => ..., 'value' => 'id', 'label' => 'name')` | [Ask](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Ask-Cards) |
| `current` | the capability an `update_` form reads its current values from (`get_<thing>` by default) | [Ask](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Ask-Cards) |
| `confirm`, `consequence` | a Confirm's question, the line under it | [Ask](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Ask-Cards#confirm) |
| `undo` | what undoes it: `array('capability' => 'return_book', 'map' => array('book_id' => 'book_id'))` (each input of the undo, from an input or the result of the change), and its button `label` (*Undo*) | [Ask](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Ask-Cards#confirm) |
| `columns`, `noun`, `variant` | a list's columns, what its rows are ("authors"), its variant (`rows`) | [Show](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Show-Cards) |
| `open` | which capability a list's row opens: `array('capability' => 'get_book', 'input' => 'id', 'from' => 'book_id')` | [Show](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Show-Cards) |
| `full` | the page that shows the same thing in full: `'/books/{id}'` | |
| `empty`, `empty_next` | what an empty list says; what would fill it: `array('lend_book')` | [Show](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Show-Cards) |
| `applies` | when an action can be done to a record: `in` or `not_in` a list | [Show](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Show-Cards#answer) |
| `done` | the assistant's line once done; `{heading}` is what it was about | |
| `next` | the capabilities it leads to (suggestions after it) | |
| `alert` | an alert on Home when rows carry a flag | [Offer](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Offer-Cards#alert) |
| `insight` | a number on Home, only with the action it calls for | below |
| `discover` | the things Home invites to browse | below |
| `working`, `async` | what a background task says while it runs; async without the attribute | [Track](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Go-and-Track-Cards#task) |
| `card`, `view`, `design` | its card view, the page whose `data-snap` part shows it, how its data is designed | [Card views](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Card-Views) |

### <a name="insight"></a>`insight`

```php
'insight' => array('label' => 'New this month', 'icon' => 'sparkles',
    'action' => array('capability' => 'list_books', 'text' => 'Browse the catalog'),
    'since' => array('field' => 'created_at', 'days' => 30),          // count only what was added lately
    'ring' => array('of' => 'list_books', 'label' => 'of the catalog', 'invert' => false)),   // and a share of another count
```

One number per read capability with the hint, shown only when there is something to act on (a count above zero) and
the person may take its `action`. Without an `action` it is never shown (G157).

### <a name="discover"></a>`discover`

On a list capability, Home shows picks of what the app is about, each saying why it is there (6 per list at most, a different few each day):

+ **for you**: more like what this person opened (only with noticing on), sharing `related`;
+ **new**: up to 2 of what was added in the last 30 days, by the field `new`;
+ **the rule**: only what is available now, not in the `unavailable` list (`available_label` says it).

| Key | What it is |
|---|---|
| `open`, `key` | how an object opens: the capability, and the field it takes |
| `title`, `meta` | what a pick shows |
| `new` | the field that says when it was added |
| `related` | what "more like it" shares (`author.id`) |
| `opened` | the requests that mean "looked at it": `array('get_book' => 'id', 'lend_book' => 'book_id')` |
| `unavailable`, `available_label` | the business rule: `array('capability' => 'list_loans', 'field' => 'book_id')` |
| `title_section` | the section's title |
## Common mistakes

+ **Hints on `#[Capability]`.** They are keys of `application/config/snap.php`; only `async` is also a flag of the
  attribute (G157).
+ **A key with a typo** is ignored silently: copy the shapes above.
+ **The file changed and nothing did**: in a long process (the queue worker, a test) the file is read once;
  `Caligrafy\Snap\Hints::forget()` reads it again.
## Related pages

+ [Snap Cards and the assistant](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant#hints)
+ [Snap: Ask cards](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Ask-Cards) · [Show cards](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Show-Cards) · [Card views](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Card-Views)
+ [API: Snap\Hints](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-hints)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/The-Snap-Assistant -->

**The assistant** of [Snap](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant) answers
what a person types, says or attaches on `/assistant` with your cards. Much of it needs no model: "What can I do?", the
name of a card or of a shortcut, "delete it" on what is on screen. With an Anthropic API key, Claude understands
anything else, looks things up with the read-only capabilities the person may call, and answers with cards. It never
changes data: a change always comes back as its Confirm. Since 2.23.0.
## With Claude

```text
/caligrafy-quill:assistant
```

Claude sets up Snap, writes `about` in `application/config/snap.php`, and asks you for an Anthropic API key if you want
the assistant to understand free text.

**Check**

+ `php caligrafer.php snap` shows the model on the `Assistant model` line, or `[--]` without a key.
+ On `/assistant`, "What can I do?" lists every card you may use.
## By hand

1. **Without a key**, the assistant works at once: `Route::snap();` in `web.php`, `php caligrafer.php snap install`.
2. **With Claude**, add to `.env`:
    ```bash
    ANTHROPIC_API_KEY=
    ```
   (a key from console.anthropic.com, API keys). The model is `claude-opus-5-5` at `low` effort; `SNAP_MODEL` and
   `SNAP_EFFORT` in `.env` change them. The `anthropic-ai/sdk` package must be installed: it is in Caligrafy's
   `composer.json` since 2.23.0 (after an `update`, `composer install`, or rebuild the Docker image).
3. **Say what the app is**, in `application/config/snap.php`:
    ```php
    'about' => 'a library app: the books of a catalog, their authors, and the books lent to people',
    ```
   `about` and `APP_NAME` in `.env` tell it what it is the assistant of.
## <a name="order"></a>Reference: how a request is answered

The first that fits:

1. **At once, without a model** (`Caligrafy\Snap\Shell`, [API](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-shell)):
   + "What can I do?" (also `what else can i do`, `what can you do`, `help`, `menu`, `?`, `options`): the menu, every card
     this person may start, by family;
   + the title of one of their [shortcuts](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Go-and-Track-Cards#shortcut):
     that shortcut, run;
   + the title or the name of a card ("the catalog", "lend a book", "list_loans"): that card;
   + a follow-up on the record on screen, a verb and "it", "this", "that", "this one", "that one" or "this book":
     `delete`/`remove`, `change`/`edit`/`update`/`fix`, `lend`/`loan`, `return`, `open`/`show`/`see`, which open
     `delete_<thing>`, `update_<thing>`, `lend_<thing>`, `return_<thing>` or `get_<thing>` for that record. Anything
     longer ("lend it to Sam") goes to the model, with the conversation's memory.
2. **Claude** (`Caligrafy\Snap\Planner`, [API](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-planner)),
   when it is on: it reads the request with the conversation so far, what is on screen and what the person chose. It
   may look things up with the read-only capabilities the person may call, as tools run with their permissions (6
   steps at most), and answers with `show_cards`: which capability, with which values, and one sentence of caption.

**What the model may never do is enforced in code, not in the prompt.** Every card it names goes through `Snap\Flow`
like any other: a read runs, a change comes back as an Ask: Confirm whose token only the person's click sends. The model
never sees a token and never runs a change. Tool results and attached files are the app's data, never instructions.

**Attachments.** The + attaches up to 3 files, 5 MB in all: PNG, JPEG, GIF, WebP, PDF, plain text, CSV, Markdown. Without
the model, attached files get a message instead of an answer.

**The keyboard.** ⌥K / Alt+K to type, ⌥M / Alt+M to talk.
## <a name="test"></a>Testing

Fake the model with `Caligrafy\Snap\Planner::$transport` (set it back to `null` in `tearDown`), and call `snap_ask`
with `$this->action()`: it is a web-only capability. The Snap tables must be in the test database
(`platform install` with the test settings).

```php
Caligrafy\Snap\Planner::$transport = function (array $request) {
    return (object) array('stopReason' => 'tool_use', 'content' => array((object) array('type' => 'tool_use', 'id' => 't1',
        'name' => 'show_cards', 'input' => array('caption' => 'Here it is.', 'cards' => array(array('capability' => 'list_books'))))));
};
$answer = $this->action('snap_ask', array('text' => 'show me the catalog'), $this->user(1))->describe()['data'];
```

The designed cards have their own fake, `Caligrafy\Snap\Designer::$transport`, or keep to the rules with
`Caligrafy\Snap\Designer::$model = false` (since 2.24.1).
## Common mistakes

+ **The assistant only answers the names of cards** (G156): `ANTHROPIC_API_KEY` is missing, or the `anthropic-ai/sdk`
  package is not installed.
+ **Forcing a tool in your own calls to Claude** (`toolChoice` of type `tool` or `any`) answers `400` on the current
  Claude models; Snap uses a structured output instead (G161).
+ **A test that fakes the planner on 2.24.0** also received the designer's requests: since 2.24.1 the designer has its
  own fake (G162).
+ **`/assistant` throws `LogicException`**: `Route::snap()` needs `Auth::authentication(...)` above it (G154).
## Related pages

+ [Snap Cards and the assistant](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant#assistant)
+ [Snap: Ask cards](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Ask-Cards#confirm): consent
+ [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App)
+ [API: Snap](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap) · [Snap\Conversation](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Conversation)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models -->

A **model** is a PHP class that stands for one table: one `Book` object is one row of `books`. Your capabilities
read and write rows through models and the [query builder](https://github.com/caligrafy/caligrafy-quill/wiki/Queries)
(`Book::where('author_id', 1)->get()`, `Book::find(3)`, `Book::insert($input)`), and every page, REST
call, Vue app and AI agent reaches the data through those capabilities. This page makes the tables of the Bookshelf
(authors, books, tags, loans) and their models.

> #### ![](https://github.com/caligrafy/caligrafy-quill/blob/master/public/images/resources/play.png) [CRUD operations on a database](https://www.youtube.com/watch?v=kNdoaSi6pcE&list=PLsJG81fLk3_UNfTuqjCbcz1S_xbram35e)
>
> An older video: it uses a controller. Today the same work goes in a capability, as below.
## With Claude

Ask for the resource with the `new-resource` skill of the Claude Code plugin, with its fields:

```text
/caligrafy-quill:new-resource Book title:string published_year:int summary:text author:fk
```

Claude writes:
+ `application/models/Book/create_db.sql`: the table, `CREATE TABLE IF NOT EXISTS`, its foreign key named
  `fk_<table>_<column>`;
+ `application/models/Book/Book.php`: the model, one public property per column;
+ the capabilities `list_books`, `get_book`, `create_book`, `update_book` and `delete_book` in
  `application/services/Books/`, which use the query builder;
+ their routes in `application/config/routing/web.php` (REST, pages, forms), and the views when you want pages.

It then offers to run the SQL (`/caligrafy-quill:db application/models/Book/create_db.sql`). When the table already
holds data, it writes a [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations) instead.

**Check** before you say OK:
+ the primary key is `id`, each foreign key column is `<parent>_id` with the same type as the parent's `id`
  (`INT UNSIGNED` for `INT UNSIGNED`);
+ the model has a property for every column, and no `find()` method of its own;
+ the table name is the class name in lower case plus `s` (`Book` -> `books`), or the model declares
  `protected static $tableName`;
+ `php caligrafer.php capabilities` lists the new capabilities, and `php caligrafer.php call get_book id=1` answers.
## <a name="modelfundamentals"></a>By hand

You have a project made with the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart) and its
Docker server. Run every command in the container: `docker compose exec dev-box php caligrafer.php ...` (without
Docker, drop `docker compose exec dev-box`).

1. **Check the database settings.** Open `.env`. The Quickstart wrote them; they must read:
    ```text
    DB_ACTIVATE=true
    DB_CONNECTION=mysql
    DB_HOST=mysql
    DB_PORT=3306
    DB_DATABASE=caligrafy
    DB_USERNAME=root
    DB_PASSWORD=root
    ```
    `DB_HOST=mysql` and `DB_PORT=3306` are the database inside the Docker network. Without Docker, use your MySQL's
    host and port (`127.0.0.1`, not `localhost`, so that the port is used). Then run
    `docker compose exec dev-box php caligrafer.php doctor --only database`: every line must be `OK`.

2. **Write the tables.** Create `application/models/Bookshelf/create_db.sql`:
    ```sql
    /* The Bookshelf tables. CREATE TABLE IF NOT EXISTS: safe to run again, it never drops anything.
     * Run it with: php caligrafer.php sql application/models/Bookshelf/create_db.sql
     */
    CREATE TABLE IF NOT EXISTS authors (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT,
        name VARCHAR(150) NOT NULL,
        bio TEXT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;

    CREATE TABLE IF NOT EXISTS books (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT,
        title VARCHAR(200) NOT NULL,
        published_year SMALLINT UNSIGNED NOT NULL,
        summary TEXT NULL,
        author_id INT UNSIGNED NOT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY idx_books_author_id (author_id),
        CONSTRAINT fk_books_author_id FOREIGN KEY (author_id) REFERENCES authors (id)
            ON UPDATE CASCADE ON DELETE RESTRICT
    ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;

    CREATE TABLE IF NOT EXISTS tags (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT,
        name VARCHAR(60) NOT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY uq_tags_name (name)
    ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;

    CREATE TABLE IF NOT EXISTS books_tags (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT,
        book_id INT UNSIGNED NOT NULL,
        tag_id INT UNSIGNED NOT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY uq_books_tags (book_id, tag_id),
        CONSTRAINT fk_books_tags_book_id FOREIGN KEY (book_id) REFERENCES books (id) ON UPDATE CASCADE ON DELETE CASCADE,
        CONSTRAINT fk_books_tags_tag_id FOREIGN KEY (tag_id) REFERENCES tags (id) ON UPDATE CASCADE ON DELETE CASCADE
    ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;

    CREATE TABLE IF NOT EXISTS loans (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT,
        book_id INT UNSIGNED NOT NULL,
        borrower VARCHAR(100) NOT NULL,
        due_on DATE NOT NULL,
        returned_at DATETIME NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY idx_loans_book_id (book_id),
        CONSTRAINT fk_loans_book_id FOREIGN KEY (book_id) REFERENCES books (id) ON UPDATE CASCADE ON DELETE CASCADE
    ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
    ```
    The names follow the conventions the [relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships)
    read: a primary key `id`, a foreign key `<parent in the singular>_id` (`author_id`) of the same type as the
    parent's `id`, and the table that links books and tags named `books_tags` with `book_id` and `tag_id`. Each
    constraint name is unique in the database (`fk_<table>_<column>`).

3. **Create them.** Run:
    ```bash
    docker compose exec dev-box php caligrafer.php sql application/models/Bookshelf/create_db.sql
    ```
    ```text
     application/models/Bookshelf/create_db.sql run on caligrafy
    ```
    Online, the deploy step runs this file on its own when it is new or changed. From now on, a change to one of
    these tables is a [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations): never edit the
    file once it ran.

4. **Add sample rows.** Create `application/models/Bookshelf/seed.sql`:
    ```sql
    /* Sample rows for the Bookshelf. INSERT IGNORE skips the rows whose id exists, so it can run twice.
     * Run it with: php caligrafer.php sql application/models/Bookshelf/seed.sql
     */

    INSERT IGNORE INTO authors (id, name, bio) VALUES
        (1, 'Ursula K. Le Guin', 'American author of science fiction and fantasy, known for the Earthsea books.'),
        (2, 'Octavia E. Butler', 'American science fiction author, the first to receive a MacArthur fellowship.'),
        (3, 'Italo Calvino', 'Italian writer of playful, inventive novels and short stories.');

    INSERT IGNORE INTO books (id, title, published_year, summary, author_id) VALUES
        (1, 'A Wizard of Earthsea', 1968, 'A gifted boy learns magic and must face the shadow he set loose.', 1),
        (2, 'The Left Hand of Darkness', 1969, 'An envoy visits a planet whose people have no fixed sex.', 1),
        (3, 'Kindred', 1979, 'A young woman is pulled back in time to a plantation in Maryland.', 2),
        (4, 'Parable of the Sower', 1993, 'In a collapsing California, a teenager starts a new belief system.', 2),
        (5, 'Invisible Cities', 1972, 'Marco Polo describes imaginary cities to the emperor Kublai Khan.', 3);

    INSERT IGNORE INTO tags (id, name) VALUES (1, 'fantasy'), (2, 'science fiction'), (3, 'classic');

    INSERT IGNORE INTO books_tags (id, book_id, tag_id) VALUES
        (1, 1, 1), (2, 1, 3), (3, 2, 2), (4, 2, 3), (5, 3, 2), (6, 4, 2), (7, 5, 3);

    INSERT IGNORE INTO loans (id, book_id, borrower, due_on, returned_at) VALUES
        (1, 1, 'Ana', '2026-11-20', NULL),
        (2, 3, 'Ben', '2026-10-30', '2026-10-28 10:00:00'),
        (3, 3, 'Chloe', '2026-11-25', NULL);
    ```
    Run it: `docker compose exec dev-box php caligrafer.php sql application/models/Bookshelf/seed.sql`
    (it prints ` application/models/Bookshelf/seed.sql run on caligrafy`). The deploy step never runs a `seed.sql`.

5. **Write the models.** One file per table, in `application/models/Bookshelf/`, one public property per column.

    `application/models/Bookshelf/Author.php`:
    ```php
    <?php

    use Caligrafy\Model;

    // One Author = one row of the authors table
    class Author extends Model
    {
        public $id;
        public $name;
        public $bio;
        public $created_at;
        public $modified_at;
    }
    ```
    `application/models/Bookshelf/Book.php`:
    ```php
    <?php

    use Caligrafy\Model;

    // One Book = one row of the books table
    class Book extends Model
    {
        public $id;
        public $title;
        public $published_year;
        public $summary;
        public $author_id;
        public $created_at;
        public $modified_at;
    }
    ```
    `application/models/Bookshelf/Tag.php`:
    ```php
    <?php

    use Caligrafy\Model;

    // One Tag = one row of the tags table
    class Tag extends Model
    {
        public $id;
        public $name;
        public $created_at;
        public $modified_at;
    }
    ```
    `application/models/Bookshelf/Loan.php`:
    ```php
    <?php

    use Caligrafy\Model;

    // One Loan = one row of the loans table: who borrowed which book, until when
    class Loan extends Model
    {
        public $id;
        public $book_id;
        public $borrower;
        public $due_on;
        public $returned_at;
        public $created_at;
        public $modified_at;
    }
    ```
    `Book::query()` and `Book::find()` read the table `books`: the class name in lower case plus `s`. The models need
    no relationship methods: the [relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships)
    are loaded with `with()`.

6. **<a name="modelinterface"></a>Read a row in a capability.** Only capabilities touch models. Create the
   capability `get_book` with `docker compose exec dev-box php caligrafer.php service Bookshelf/GetBook --scope books:read --read-only`,
   then make `application/services/Bookshelf/GetBook.php` read:
    ```php
    <?php

    use Caligrafy\Capability;
    use Caligrafy\Context;
    use Caligrafy\Service;
    use Caligrafy\ServiceError;

    // get_book: one book with its author, or "not found"
    #[Capability(
        name: 'get_book',
        description: 'Returns one book of the catalog with its author (id, name, bio), by the id of the book.',
        scope: 'books:read',
        readOnly: true,
        public: true
    )]
    class GetBook extends Service
    {
        public $rules = array('id' => 'required|integer');
        public $descriptions = array('id' => 'The id of the book');

        public function handle(array $input, Context $context)
        {
            $book = Book::with('author')->find($input['id']);
            if (!$book) {
                throw ServiceError::notFound("There is no book #{$input['id']}");
            }
            return $book;
        }
    }
    ```
    Run `docker compose exec dev-box php caligrafer.php call get_book id=3`:
    ```json
    {
        "data": {
            "id": 3,
            "title": "Kindred",
            "published_year": 1979,
            "summary": "A young woman is pulled back in time to a plantation in Maryland.",
            "author_id": 2,
            "created_at": "2026-11-07 23:23:48",
            "modified_at": "2026-11-07 23:23:48",
            "author": {
                "id": 2,
                "name": "Octavia E. Butler",
                "bio": "American science fiction author, the first to receive a MacArthur fellowship.",
                "created_at": "2026-11-07 23:23:48",
                "modified_at": "2026-11-07 23:23:48"
            }
        }
    }
    ```
    (Your dates differ.) The capability returns a `Book` with its `author` ([Relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships));
    every channel gets it as plain data. `id=99` gives
    `{"error": {"code": "not_found", "message": "There is no book #99"}}`. Writing a capability, and serving it to
    pages, REST and agents, is on [Build once](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#service).

**Check:**
+ `docker compose exec mysql mysql -uroot -proot caligrafy -e "SHOW TABLES"` lists `authors`, `books`, `books_tags`,
  `loans` and `tags` (beside the `caligrafy_*` framework tables);
+ `docker compose exec dev-box php caligrafer.php call get_book id=3` returns *Kindred*;
+ each model has exactly the columns of its table.
## <a name="modelmethods"></a>Reference

**Reading: the query builder on the model class.** Every call returns models of the class (`Book`), on its table.
The full list is on [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries).

| Call | Returns |
|---|---|
| `Book::find(3)` | the `Book` of id 3, or `null` |
| `Book::where('author_id', 1)->get()` | a list of `Book` (empty when none) |
| `Book::where('title', 'Kindred')->first()` | the first `Book`, or `null` |
| `Book::with('author')->find(3)` | the book, with `author` (an array) |
| `Book::where('author_id', 1)->count()` | a number |
| `Book::query()->orderBy('title')->paginate(20, $page)` | `['data', 'total', 'page', 'per_page', 'pages']` |
| `Book::query()` | the query builder on `books`, to build on |

The calls a model class forwards to the query builder: `query`, `find`, `select`, `where`, `orWhere`, `whereIn`,
`whereNotIn`, `whereNull`, `whereNotNull`, `whereBetween`, `orderBy`, `latest`, `oldest`, `limit`, `offset`, `with`,
`withCount`, `first`, `value`, `pluck`, `count`, `exists`, `paginate`, `chunk`, `get`, `insert`, `input`, `arrays`.
`search()` is not one of them: write `Book::query()->search([...], $words)`.

**Writing: the query builder on the model class.** The full list is on
[Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries#write).

| Call | What it does | Returns |
|---|---|---|
| `Book::insert($input)` | one `INSERT` of the values of `$input` (an array; arrays and objects in it are written as JSON) | the id of the new row |
| `Book::where('id', $id)->update($changes)` | `UPDATE ... WHERE id = ?` | how many rows changed |
| `Book::where('id', $id)->delete()` | `DELETE ... WHERE id = ?` | how many rows were deleted (`0`: no such row) |
| `Book::where('id', $id)->increment('stock', 2)` | adds to a number column (`decrement()` too) | how many rows changed |

`update()`, `delete()`, `increment()` and `decrement()` refuse to run without a `where()`, so a missing condition never
changes every row. Every value is bound. A capability that creates a book returns it read back:
`$id = Book::insert($input); return Book::with('author')->find($id);`.

**The table of a model**

| The model | `Book::query()` reads |
|---|---|
| `class Book` | `books` (the class name in lower case + `s`) |
| `class Category` | `categories` (consonant + `y` -> `ies`; `s`, `x`, `z`, `ch`, `sh` -> `es`) |
| `class BookReview` | `bookreviews` (no `_`): declare `protected static $tableName = 'book_reviews';` |
| `class Person` with `protected static $tableName = 'people';` | `people` |

**Database settings** (`.env`)

| Setting | Default in `.env.example` | Meaning |
|---|---|---|
| `DB_ACTIVATE` | `false` | `true` connects; without it every query fails with `[ERROR 2003]` |
| `DB_CONNECTION` | `mysql` | the PDO driver |
| `DB_HOST` | `localhost` | `mysql` with the Docker server; `127.0.0.1` to reach a port over TCP |
| `DB_PORT` | `3306` | added to the connection unless `DB_HOST` already has `;port=` |
| `DB_DATABASE`, `DB_USERNAME`, `DB_PASSWORD` | `databasename`, `root`, `root` | the database and its account |
| `DB_TIMEZONE` | empty | empty: MySQL uses PHP's `SERVER_TIMEZONE`; `server` keeps MySQL's own |
## <a name="querybuilder"></a>Other ways

These still work. Use them only in older code; the prescriptive way is in brackets.

+ **A model in a controller** [a capability]: `$this->associate('Book', 'books');` then `$this->model->find(1)`. See
  [Controllers](https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers).
+ **The methods of a model object** [`Book::insert()`, `Book::where('id', $id)->update()` and `->delete()` above]:
  `new Book('books')` gives an object on the table you name, and its methods write one row:

    | Method | What it does | Returns |
    |---|---|---|
    | `(new Book('books'))->create($input)` | `INSERT` of the values of `$input` (an array or an object) | the new `Book`, read back |
    | `(new Book('books'))->update($changes, $id)` | `UPDATE ... WHERE id = ?`; nothing when the row does not exist or nothing is left to save | the `Book` read back, or `null` |
    | `(new Book('books'))->delete($id)` | `DELETE ... WHERE id = ?` | an empty array |
    | `$book->save()` | `update()` when `$book->id` is set, otherwise `create()` | the `Book` read back |
    | `$book->toArray()` | the object as an array | array |
    | `(new Book('books'))->find($id)` | `SELECT * ... WHERE id = ?` (the older form of `Book::find`) | `Book` or `null` |

    `create()`, `update()` and `save()` write only the columns the table has (a helper property such as
    `public $errors` is left out), and only values that are not `null` (`0`, `''` and `false` are written; `false` as
    `0`). A property left `null` keeps the column's current value or its default. Arrays and objects are written as
    JSON. Every value is bound; the column names must be letters, digits and `_`. On such an object,
    `$book->where(...)` uses the table it was given.
+ **`all()` with SQL clauses** [`Book::where(...)->orderBy(...)->limit(...)->get()`]: the clauses are added to the SQL as
  they are, so they hold their keywords, and values go in `bindings`, never in the text:
    ```php
    $books = (new Book('books'))->all(array(
        'condition' => 'WHERE author_id = ?',
        'order' => 'ORDER BY title',
        'limit' => 'LIMIT 10',
        'bindings' => array(1)
    ));
    ```
+ **`search($columns, $pattern)`** [`Book::query()->search(['title', 'summary'], $words)`]:
  `(new Book('books'))->search('title,summary', '%shadow%')` takes a `LIKE` pattern as it is (`%` and `_` are
  wildcards); the columns must be letters, digits and `_`.
+ **SQL the query builder does not write** (a join with `GROUP BY`, a subquery, a database function): a method of the
  model with `Database::execute()` and `?` placeholders:
    ```php
    public function findByIsbn($isbn)
    {
        $rows = Database::toArray(Database::execute('SELECT * FROM ' . $this->table . ' WHERE isbn = ? LIMIT 1', [$isbn]));
        return !empty($rows[0]) ? $this->arrayToModel($rows[0]) : null;
    }
    ```
+ **Relationship methods in the model** (`hasOne()`, `hasMany()`, `belongsToMany()`) [`with()`]: see
  [Relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships#methods).
## Common mistakes

+ **A `find()` method in your model** (G122): `$book->find()` then runs yours, and `Book::find(3)` fails with
  "Non-static method cannot be called statically". Leave `find()` out, or call `Book::query()->find(3)`.
+ **A table name the model cannot guess** (G123): `BookReview` reads `bookreviews`. Declare
  `protected static $tableName = 'book_reviews';` (protected or public; a private one is not seen).
+ **A value written into SQL** (G2, G8): `all(['condition' => "WHERE title = '$title'"])` lets a visitor change the
  query. Use the query builder, or `?` and `bindings`.
+ **`DB_HOST=localhost` with a port** (G3): PDO then uses the MySQL socket and ignores `DB_PORT`. Use `127.0.0.1`.
+ **A foreign key of another type** (G10): `INT` toward `INT UNSIGNED` fails with "incompatible". Give it the parent's type.
+ **Editing `create_db.sql` after it ran**: a database that has the table keeps the old one. Write a
  [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations).
## Related pages

+ [Relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships): authors, books, tags, loans together
+ [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries): filters, paging, counts, writes, transactions
+ [Migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations): changing a table that holds data
+ [Build once: services, capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP)
+ [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#sql): `sql`, `migrate`, `call`


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships -->

Tables point at each other: a book has one author (`books.author_id`), an author has many books, a book has many
loans, and books and tags are linked many to many through `books_tags`. A capability loads those **related rows** with
`with()` of the [query builder](https://github.com/caligrafy/caligrafy-quill/wiki/Queries): one query for the books,
one more per relation, never one query per book. The relations follow the names of your tables, so the models need no
code for them. This page uses the Bookshelf tables of [Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models).

```php
$book    = Book::with('author', 'loans', ['tags' => ['pivot' => true]])->find(3);   // its author, its loans, its tags
$authors = Author::withCount('books')->orderBy('name')->get();                       // each author with books_count
```

> #### ![](https://github.com/caligrafy/caligrafy-quill/blob/master/public/images/resources/play.png) [Relationships](https://www.youtube.com/watch?v=o6knV88iCkw&list=PLsJG81fLk3_UNfTuqjCbcz1S_xbram35e)
>
> An older video: it shows the relationship methods of the model (under "Other ways" below).
## With Claude

Ask for the capability with the `new-capability` skill, and say which related rows it returns:

```text
/caligrafy-quill:new-capability get_book books:read read-only: one book with its author, its loans and its tags
```

Claude writes `application/services/Bookshelf/GetBook.php` (or the folder of your resource), reads the rows with
`Book::with(...)`, and never queries in a loop. For a resource with a parent (`/caligrafy-quill:new-resource Book ... author:fk`),
it writes the foreign key `author_id` and its constraint in `create_db.sql`.

**Check** before you say OK:
+ the capability reads related rows with `with()` or `withCount()`, not a query inside a `foreach`;
+ many-to-many relations say `['pivot' => true]` (or the pivot's name);
+ `php caligrafer.php call get_book id=3` shows the related rows under their names (`author`, `loans`, `tags`).
## By hand

Run every command in the Docker container: `docker compose exec dev-box php caligrafer.php ...` (without Docker, drop
`docker compose exec dev-box`).

1. **A book with its author, its loans and its tags.** Make `application/services/Bookshelf/GetBook.php` read:
    ```php
    <?php

    use Caligrafy\Capability;
    use Caligrafy\Context;
    use Caligrafy\Service;
    use Caligrafy\ServiceError;

    #[Capability(
        name: 'get_book',
        description: 'Returns one book by its id, with its author, its tags and its loans.',
        scope: 'books:read',
        readOnly: true,
        public: true
    )]
    class GetBook extends Service
    {
        public $rules = array('id' => 'required|integer');

        public $descriptions = array('id' => 'The id of the book');

        public function handle(array $input, Context $context)
        {
            $book = Book::with('author', 'loans', array('tags' => array('pivot' => true)))->find($input['id']);
            if (!$book) {
                throw ServiceError::notFound('There is no book #' . $input['id']);
            }
            return $book;
        }
    }
    ```
    Run `docker compose exec dev-box php caligrafer.php call get_book id=3`:
    ```json
    {
        "data": {
            "id": 3,
            "title": "Kindred",
            "published_year": 1979,
            "summary": "A young woman is pulled back in time to a plantation in Maryland.",
            "author_id": 2,
            "created_at": "2026-11-07 23:23:48",
            "modified_at": "2026-11-07 23:23:48",
            "author": {
                "id": 2,
                "name": "Octavia E. Butler",
                "bio": "American science fiction author, the first to receive a MacArthur fellowship.",
                "created_at": "2026-11-07 23:23:48",
                "modified_at": "2026-11-07 23:23:48"
            },
            "loans": [
                {"id": 2, "book_id": 3, "borrower": "Ben", "due_on": "2026-10-30", "returned_at": "2026-10-28 10:00:00", "created_at": "2026-11-07 23:23:48", "modified_at": "2026-11-07 23:23:48"},
                {"id": 3, "book_id": 3, "borrower": "Chloe", "due_on": "2026-11-25", "returned_at": null, "created_at": "2026-11-07 23:23:48", "modified_at": "2026-11-07 23:23:48"}
            ],
            "tags": [
                {"id": 2, "name": "science fiction", "created_at": "2026-11-07 23:23:48", "modified_at": "2026-11-07 23:23:48"}
            ]
        }
    }
    ```
    (Your dates differ.) Four queries ran: the book, then its author, its loans and its tags, each with
    `WHERE ... IN (...)`.

2. **Every author with the number of their books.** Run
   `docker compose exec dev-box php caligrafer.php service Bookshelf/ListAuthors --scope books:read --read-only`,
   then make `application/services/Bookshelf/ListAuthors.php` read:
    ```php
    <?php

    use Caligrafy\Capability;
    use Caligrafy\Context;
    use Caligrafy\Service;

    #[Capability(
        name: 'list_authors',
        description: 'Lists every author of the Bookshelf, sorted by name, with books_count: how many books each one has in the catalog.',
        scope: 'books:read',
        readOnly: true,
        public: true
    )]
    class ListAuthors extends Service
    {
        public function handle(array $input, Context $context)
        {
            return Author::withCount('books')->orderBy('name')->get();
        }
    }
    ```
    `docker compose exec dev-box php caligrafer.php call list_authors` returns the three authors, each with
    `books_count`: Italo Calvino `1`, Octavia E. Butler `2`, Ursula K. Le Guin `2`. `withCount()` ran one
    `GROUP BY` query for all of them.

3. **Link and unlink a tag.** The rows of a many-to-many relation live in the pivot table `books_tags`: add and remove
   them with the query builder. Run
   `docker compose exec dev-box php caligrafer.php service Bookshelf/TagBook --scope books:write`, then make
   `application/services/Bookshelf/TagBook.php` read:
    ```php
    <?php

    use Caligrafy\Capability;
    use Caligrafy\Context;
    use Caligrafy\Database;
    use Caligrafy\Service;

    #[Capability(
        name: 'tag_book',
        description: 'Adds a tag to a book (nothing changes when the book has it already) and returns the book with all its tags.',
        scope: 'books:write'
    )]
    class TagBook extends Service
    {
        public $rules = array(
            'book_id' => 'required|integer|exists,books.id',
            'tag_id' => 'required|integer|exists,tags.id'
        );

        public function handle(array $input, Context $context)
        {
            $link = array('book_id' => $input['book_id'], 'tag_id' => $input['tag_id']);
            if (!Database::table('books_tags')->where($link)->exists()) {
                Database::table('books_tags')->insert($link);
            }
            return Book::with(array('tags' => array('pivot' => true)))->find($input['book_id']);
        }
    }
    ```
    Run `docker compose exec dev-box php caligrafer.php service Bookshelf/UntagBook --scope books:write`, then make
    `application/services/Bookshelf/UntagBook.php` read:
    ```php
    <?php

    use Caligrafy\Capability;
    use Caligrafy\Context;
    use Caligrafy\Database;
    use Caligrafy\Service;

    #[Capability(
        name: 'untag_book',
        description: 'Removes a tag from a book and returns the book with the tags it has left.',
        scope: 'books:write'
    )]
    class UntagBook extends Service
    {
        public $rules = array(
            'book_id' => 'required|integer|exists,books.id',
            'tag_id' => 'required|integer'
        );

        public function handle(array $input, Context $context)
        {
            Database::table('books_tags')->where(array('book_id' => $input['book_id'], 'tag_id' => $input['tag_id']))->delete();
            return Book::with(array('tags' => array('pivot' => true)))->find($input['book_id']);
        }
    }
    ```
    Run `docker compose exec dev-box php caligrafer.php call tag_book book_id=3 tag_id=3`: *Kindred* now has the tags
    `science fiction` and `classic`. Running it again changes nothing. `call untag_book book_id=3 tag_id=3` leaves
    `science fiction`. `call tag_book book_id=3 tag_id=9` answers `"tag_id": "There is no such tag"`.

**Check:**
+ `call get_book id=3` has `author`, `loans` and `tags`;
+ `call list_authors` gives each author a `books_count`;
+ `docker compose exec mysql mysql -uroot -proot caligrafy -e "SELECT * FROM books_tags WHERE book_id = 3"` shows
  the links you made.
## Reference

### <a name="onetoone"></a><a name="onetomany"></a>How `with()` reads a name

`with()` follows the name you give and the table it is called on:

| Name | Called on | Kind | It reads | You get |
|---|---|---|---|---|
| `author` (singular) | `books` | belongs to | `books.author_id` -> `authors.id` | one row, or `null` |
| `books` (plural) | `authors` | has many | `books.author_id` = `authors.id` | a list, or `[]` |
| `loans` (plural) | `books` | has many | `loans.book_id` = `books.id` | a list, or `[]` |
| `['tags' => ['pivot' => true]]` | `books` | many to many | `books_tags.book_id` = `books.id`, `books_tags.tag_id` = `tags.id` | a list, or `[]` |
| `book.author` | `loans` | nested: the relation of a relation | `loans.book_id` -> `books.id`, then `books.author_id` -> `authors.id` | `book` with its `author` |
| `['current_loan' => ['type' => 'hasOne', 'table' => 'loans']]` | `books` | has one | `loans.book_id` = `books.id` | the first row, or `null` |

+ Singular and plural: `author` -> `authors`, `category` -> `categories`, `box` -> `boxes`. An irregular plural
  (`person`/`people`) needs `'table'`.
+ The related rows are **arrays**, also under models: `$book->author['name']`, `$book->tags[0]['name']`.
+ The key must be in the rows: `Book::select('id', 'title')->with('author')` has no `author_id`, so `author` is `null`.
+ Several names at once: `with('author', 'loans')`; one name's settings: `with(['author' => [...]])`; both:
  `with('author', ['tags' => ['pivot' => true]])`.

### <a name="manytomany"></a>Many to many: the pivot

The pivot of `books` and `tags` is `books_tags` (`<this table>_<related table>`), with `book_id` and `tag_id`. When
that table does not exist but `tags_books` does, `with()` uses `tags_books` (it tries `books_tags` first, then
remembers). `['pivot' => 'book_tag_links']` names another pivot. Write the pivot in `create_db.sql`, with a
`UNIQUE KEY` on its two columns, as on [Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models). Add and
remove links with `Database::table('books_tags')->insert([...])` and `->where([...])->delete()`, as in step 3.

### <a name="override"></a>When your names differ: the settings

```php
Book::with(['writer' => ['table' => 'authors', 'foreign_key' => 'author_id']])->find(3);   // $book->writer
Book::with(['current_loan' => ['type' => 'hasOne', 'table' => 'loans', 'query' => function ($q) { $q->whereNull('returned_at'); }]])->get();
```

| Setting | Meaning | Default |
|---|---|---|
| `type` | `belongsTo`, `hasOne`, `hasMany` or `belongsToMany` | singular name: `belongsTo`; plural: `hasMany`; with `pivot`: `belongsToMany` |
| `table` | the related table | the name in the plural (`belongsTo`, `hasOne`), the name itself (`hasMany`, `belongsToMany`) |
| `foreign_key` | belongs to: the column of this table; has one/many: the column of the related table; many to many: the pivot's column toward this table | `<name>_id` (belongs to), `<this table in the singular>_id` (the others) |
| `local_key` | the column of this table the others point at | `id` |
| `owner_key` | the column of the related table that is pointed at | `id` |
| `pivot` | `true` (the conventional pivot) or its name | none |
| `related_key` | the pivot's column toward the related table | `<name in the singular>_id` |
| `query` | a function that narrows the related rows: `function ($q) { $q->where('published_year', '<', 1970); }` | none |

A function alone is the `query` setting: `with(['loans' => function ($q) { $q->whereNull('returned_at'); }])`. An unknown
setting, or a name that is not letters, digits and `_`, is refused before any query runs.

### Counting: `withCount()`

```php
Author::withCount('books')->get();                                   // books_count on each author
Database::table('tags')->withCount(['books' => ['pivot' => true]])->pluck('books_count', 'name');
// ['fantasy' => 1, 'science fiction' => 3, 'classic' => 3]
Author::withCount(['books' => function ($q) { $q->where('published_year', '<', 1970); }])->pluck('books_count', 'name');
// ['Ursula K. Le Guin' => 2, 'Octavia E. Butler' => 0, 'Italo Calvino' => 0]
```

`withCount()` counts plural relations only (has many, many to many): `withCount('author')` is refused ("counts a
plural relation"). A row with nothing to count gets `0`.
## <a name="methods"></a>Other ways: the relationship methods of a model

Before 2.19, relations were methods of the model. They still work, for one model object at a time; `with()` replaces
them, for one row or a thousand.

```php
class Book extends Model
{
    // ... the properties

    public function author()   // the author: books.author_id -> authors.id
    {
        return $this->hasOne('Author', 'authors');
    }

    public function loans()    // the loans: loans.book_id = books.id
    {
        return $this->hasMany('Loan', 'loans');
    }

    public function tags()     // the tags, through books_tags (book_id, tag_id)
    {
        return $this->belongsToMany('Tag', 'tags');
    }
}

$book = (new Book('books'))->find(1);
$book->author()->name;           // 'Ursula K. Le Guin' (a model, or null)
$book->loans();                  // a list of Loan
$book->tags();                   // a list of Tag
$book->attach('tags', 2);        // adds the link 1-2 (call tags() first); returns the tags again
$book->detach('tags', 2);        // removes it
```

| Method | It reads | Returns |
|---|---|---|
| `hasOne($model, $table, $foreignKey = null, $localKey = null)` | the foreign key **on this model's table**: `books.author_id` -> `authors.id` (`$foreignKey` names this table's column, `$localKey` the other table's) | a model, or `null` |
| `hasMany($model, $table, $foreignKey = null, $localKey = null)` | `<table>.<this class>_id` = this id (`$foreignKey` names that column, `$localKey` a property of this model to use instead of `id`) | a list of models |
| `belongsTo(...)` | the same as `hasMany()`: it is **not** the inverse of `hasMany()`. For a child's parent, use `hasOne()` | a list |
| `belongsToMany($model, $table, $foreignKeyLocal = null, $foreignKeyJoin = null)` | the pivot `<this table>_<table>` (or `<table>_<this table>` when that one exists); its columns are `<this class>_id` and `<model>_id`. It **creates the pivot** with `CREATE TABLE IF NOT EXISTS` the first time | a list of models; `$book->pivot->tags->all` holds the rows |
| `attach($table, $id)`, `detach($table, $id)` | add or remove a pivot row; call the relationship method first | the relationship again |

The method's name is up to you; it is never saved as a column. The foreign key names come from the class name in lower
case (`Book` -> `book_id`).
## Common mistakes

+ **A query inside a `foreach`** (the N+1 problem): 50 books and their authors become 51 queries. In development the
  PHP error log says "Probable N+1 query" with the file and line (G127). Load them with `with('author')`.
+ **`with('tags')` without `pivot`** (G124): `tags` is plural, so it is read as has many: `tags.book_id`, which fails
  with "Unknown column 'book_id'". Write `with(['tags' => ['pivot' => true]])`.
+ **`belongsTo()` as the inverse of `hasMany()`** (G9): it returns the children, like `hasMany()`. Use `with('author')`
  (or `hasOne()`).
+ **A foreign key of another type than the `id` it points at** (G10): MySQL refuses the constraint. Give both
  `INT UNSIGNED`.
+ **Reading `$book->author->name`**: related rows are arrays. Write `$book->author['name']`.
## Related pages

+ [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries#eager): `with()` among the other calls
+ [Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models): the tables and the models
+ [Validation](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation#database-rules): `exists` and `unique`
+ [Build once](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#service): writing a capability


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Queries -->

The **query builder** reads and writes your tables without SQL strings. You chain a few calls, and Caligrafy writes one
SQL statement with every value bound (sent apart from the SQL, so what a person types can never change the query). It
is how a capability lists, filters, pages and counts rows, and loads related rows in one query instead of one per row.
Since 2.19.0.

**Since 2.26.0** N+1 queries are prevented by default: calling a relation method on one of several rows a query returned throws `[ERROR 2004] Lazy loading prevented` in development, with the `with('<relation>')` fix, and logs a warning in production. `->lazy()`, `#[Caligrafy\Lazy]` or `STRICT_RELATIONS=false` allow it. See [eager loading](https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Eager-Loading).

```php
use Caligrafy\Database;

$rows  = Database::table('books')->where('published_year', '<', 1975)->orderBy('title')->limit(10)->get();   // arrays
$books = Book::where('author_id', 1)->with('author')->paginate(20);                                        // Book models
```

+ `Database::table('books')` gives **arrays**, one per row.
+ `Book::query()`, or any call on the model class (`Book::where(...)`, `Book::find(3)`, `Book::with(...)`), gives
  **`Book` models**, on the model's table ([Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models)).

The examples use the Bookshelf tables and sample rows of [Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models).
## With Claude

Say what the list filters, sorts and returns:

```text
/caligrafy-quill:new-capability list_books books:read read-only: the books sorted by title, 20 per page, with their author and tags; filters author_id and search (title or summary)
```

Claude writes the capability with the query builder: `Book::with(...)->orderBy(...)`, a `where()` per filter given,
`search()` for words, and `paginate(20, $input['page'] ?? 1)` with `'page' => 'integer'` in `$rules`.

**Check** before you say OK:
+ no SQL string is built from an input, and no query runs inside a loop;
+ every input `handle()` reads is in `$rules` (`page` too);
+ `update()` and `delete()` of a query have a `where()`;
+ `php caligrafer.php call list_books search=shadow` returns the right rows.
## <a name="capability"></a>By hand

Run the commands in the Docker container: `docker compose exec dev-box php caligrafer.php ...` (without Docker, drop
`docker compose exec dev-box`).

1. **Create the capability.** Run:
    ```bash
    docker compose exec dev-box php caligrafer.php service Bookshelf/ListBooks --scope books:read --read-only
    ```
2. **Write the query.** Make `application/services/Bookshelf/ListBooks.php` read:
    ```php
    <?php

    use Caligrafy\Capability;
    use Caligrafy\Context;
    use Caligrafy\Service;

    #[Capability(
        name: 'list_books',
        description: 'Lists the books of the Bookshelf catalog, sorted by title, 20 per page, each with its author and its tags. Filters: author_id, search (words of the title or the summary). Returns data (the books), total, page, per_page and pages.',
        scope: 'books:read',
        readOnly: true,
        public: true
    )]
    class ListBooks extends Service
    {
        public $rules = array(
            'author_id' => 'integer',
            'search' => 'max_len,100',
            'page' => 'integer'
        );

        public $descriptions = array(
            'author_id' => 'Optional: only the books of this author',
            'search' => 'Optional: words to find in the title or the summary',
            'page' => 'Optional: the page, 1 by default (20 books per page)'
        );

        public function handle(array $input, Context $context)
        {
            $query = Book::with('author', array('tags' => array('pivot' => true)))->orderBy('title');
            if (!empty($input['author_id'])) {
                $query->where('author_id', $input['author_id']);
            }
            if (!empty($input['search'])) {
                $query->search(array('title', 'summary'), $input['search']);
            }
            return $query->paginate(20, $input['page'] ?? 1);
        }
    }
    ```
    A query built step by step changes as you call it: `$query->where(...)` adds to `$query`.
3. **Run it.**
    ```bash
    docker compose exec dev-box php caligrafer.php call list_books search=shadow
    ```
    returns one page: `"data"` holds *A Wizard of Earthsea* with its `author` and its `tags`, then
    `"total": 1, "page": 1, "per_page": 20, "pages": 1`. With `author_id=2` the page holds *Kindred* and *Parable of
    the Sower* (`"total": 2`); with `author_id=abc` the answer is
    `"author_id": "The Author Id field must be a number without a decimal"`.

One capability, and the page, the REST API, the Vue app and agents all get the same filtered, paged list
([Build once](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#web)).

**Check:**
+ `call list_books search=shadow` gives `"total": 1`;
+ `call list_books search=50%` gives `"total": 0`: `%` is a character to find, not a wildcard;
+ `call list_books page=2` gives `"data": []` with `"page": 2` (there are fewer than 21 books).
## <a name="read"></a>Reference: building a query

```php
Book::where('author_id', 1)->get();                               // author_id = 1
Book::where('published_year', '<', 1975)->where('author_id', 1)->get();   // AND
Book::where('published_year', '<', 1970)->orWhere('author_id', 3)->get(); // OR
Book::where(['author_id' => 1, 'published_year' => 1968])->get(); // several equalities, in parentheses
Book::where(function ($q) {                                       // a group in parentheses
    $q->where('published_year', '<', 1970)->orWhere('author_id', 3);
})->where('summary', '!=', null)->get();

Book::whereIn('id', [1, 2, 3])->get();                            // whereNotIn too
Book::whereNull('summary')->get();                                // whereNotNull too
Book::whereBetween('published_year', [1960, 1980])->get();        // both ends included
Book::query()->search(['title', 'summary'], $words)->get();       // title or summary contains the words
Book::query()->latest()->limit(5)->offset(5)->get();              // newest first (created_at); oldest() the other way
Book::query()->select('id', 'title as name')->arrays()->get();    // two columns, renamed
```

The SQL they write (`toSql()` and `getBindings()` show it, without running it):

| Query | SQL | Bindings |
|---|---|---|
| `Book::where(['author_id' => 1, 'published_year' => 1968])` | ``SELECT * FROM `books` WHERE (`author_id` = ? AND `published_year` = ?)`` | `[1, 1968]` |
| the group above | ``... WHERE (`published_year` < ? OR `author_id` = ?) AND `summary` IS NOT NULL`` | `[1970, 3]` |
| `Book::whereIn('id', [1, 2, 3])->whereNull('summary')->whereBetween('published_year', [1960, 1980])` | ``... WHERE `id` IN (?, ?, ?) AND `summary` IS NULL AND `published_year` BETWEEN ? AND ?`` | `[1, 2, 3, 1960, 1980]` |
| `Book::query()->search(['title', 'summary'], 'shadow 50%')` | ``... WHERE (`title` LIKE ? OR `summary` LIKE ?)`` | `['%shadow 50\%%', '%shadow 50\%%']` |
| `Book::query()->latest()->limit(5)->offset(5)` | ``SELECT * FROM `books` ORDER BY `created_at` DESC LIMIT 5 OFFSET 5`` | `[]` |
| `Book::query()->select('id', 'title as name')` | ``SELECT `id`, `title` AS `name` FROM `books` `` | `[]` |

| Call | Meaning |
|---|---|
| `where($column, $value)` | `=`; `where($column, null)` is `IS NULL` |
| `where($column, $operator, $value)` | operators `=`, `!=`, `<>`, `<`, `>`, `<=`, `>=`, `like`, `not like`; `where($column, '!=', null)` is `IS NOT NULL` |
| `where([$column => $value, ...])`, `where(function ($q) {...})` | equalities joined by `AND`, a group; both in parentheses |
| `orWhere(...)` | the same forms, joined by `OR` |
| `whereIn($column, $list)`, `whereNotIn($column, $list)` | an empty list: `whereIn` matches no row, `whereNotIn` adds no condition |
| `whereNull($column)`, `whereNotNull($column)`, `whereBetween($column, [$from, $to])` | |
| `search($columns, $words)` | `(c1 LIKE ? OR c2 LIKE ?)` with `%words%` bound; `%` and `_` in the words are escaped; empty words add no condition |
| `orderBy($column, 'asc' or 'desc')`, `latest($column = 'created_at')`, `oldest($column = 'created_at')` | |
| `limit($n)`, `offset($n)` | whole numbers >= 0 |
| `select(...$columns)` | `'id'`, `'books.*'`, `'title as name'`; one array works too |
| `arrays()` | rows stay arrays (undoes the models of `Book::query()`) |
| `input($array)` | where `paginate()` reads `page` instead of the query string |
| `with(...)`, `withCount(...)` | related rows and counts: [Relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships) |

**Names are checked, values are bound.** A table or column name must be letters, digits and `_` (or `table.column`);
anything else is refused before any SQL runs: `[ERROR 2001] Invalid table or column name 'name; DROP': letters, digits
and _ only, with one optional prefix (table.column)`. Another operator gives `[ERROR 2001] Operator not allowed: use
=, !=, <>, <, >, <=, >=, like or not like`. A boolean is bound as `0`/`1`, a `DateTime` as `Y-m-d H:i:s`; an array
value is refused (use `whereIn`).

**Selected columns and models.** A model has every property its class declares, so
`Book::query()->select('id', 'title')->get()` gives `Book` models whose other columns are `null` (and a capability
returns them, `null`s included). For only the columns you selected (a CSV export, a small list), add `arrays()`:
`Book::query()->select('id', 'title')->arrays()->get()` gives `[['id' => 1, 'title' => 'A Wizard of Earthsea'], ...]`,
as `Database::table('books')->select('id', 'title')->get()` does.
## Reference: getting the rows

| To get | Call | Returns |
|---|---|---|
| every row | `get()` | a list (empty when none) |
| the first row | `first()` | one row, or `null` |
| one row by id | `find(3)`, `find($value, 'isbn')` | one row, or `null` |
| one value | `value('title')` | `'Kindred'`, or `null` |
| one column | `pluck('title')`, `pluck('title', 'id')` | `['A Wizard of Earthsea', ...]`, `[1 => 'A Wizard of Earthsea', ...]` |
| how many | `count()` | a number (order and limit ignored) |
| whether any | `exists()` | `true` or `false` |
| a page | `paginate(20, $page)` | `['data', 'total', 'page', 'per_page', 'pages']` |
| many rows, in parts | `chunk(500, function ($rows, $part) { ... })` | `true`, or `false` when the function returned `false` |

`pluck()` also takes a count of `withCount()` or a relation of `with()`:
`Author::withCount('books')->pluck('books_count', 'name')` gives `['Ursula K. Le Guin' => 2, ...]`. `chunk()` reads in
`id` order unless the query has an order.

### <a name="paging"></a>Paging

```php
$page = Book::query()->orderBy('title')->paginate(2, 2);
// ['data' => [Kindred, Parable of the Sower], 'total' => 5, 'page' => 2, 'per_page' => 2, 'pages' => 3]
```

+ Without a page number, `paginate()` reads `page` from the query string (`?page=2`). In a capability, pass the page
  of its input, as in the steps above: REST, an agent or the command line have no query string.
+ A page number that is not a whole number >= 1 is page 1. A page past the last one gives `'data' => []` (and runs
  no second query). `pages` is at least 1.

### <a name="eager"></a>Related rows: `with()` and the N+1 problem

Listing 50 books and then reading each one's author runs 51 queries (the N+1 problem). `with()` runs two: one for the
books, one for all their authors (`WHERE id IN (...)`).

```php
$books   = Book::with('author', ['tags' => ['pivot' => true]])->get();   // author: a row or null; tags: a list
$authors = Author::withCount('books')->get();                            // books_count on each
$loan    = Database::table('loans')->with('book.author')->first();       // the loan, its book, the book's author
```

The names, the conventions and the settings are on
[Relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships).

**The N+1 warning.** While you develop (`APP_ENV` other than `production`), when the same query runs 10 times in one
request, Caligrafy writes one line in the PHP error log:

```text
[Caligrafy] Probable N+1 query: the same SELECT ran 10 times in this request (select * from `books` where `id` = ? limit ?), from <the file>:<the line>. Load the rows once with with(): Database::table('books')->with('author')->get() or Book::with('author')->get().
```

Add a `with()` where it says. Production does not count.
## <a name="write"></a>Reference: writing rows

```php
$id = Database::table('tags')->insert(['name' => 'poetry']);                    // the new id, as a string: "4"
Database::table('tags')->insert([['name' => 'essay'], ['name' => 'travel']]);   // several rows, one statement

Database::table('tags')->where('id', $id)->update(['name' => 'poems']);         // 1: the rows changed
Book::where('id', 1)->increment('published_year');                              // also decrement('stock', 2)
Database::table('tags')->whereIn('name', ['essay', 'travel', 'poems'])->delete(); // 3: the rows deleted
```

+ `insert()` takes one row, or a list of rows that all have the same columns. Arrays and objects are written as JSON,
  booleans as `0`/`1`.
+ `update()`, `delete()`, `increment()` and `decrement()` need a `where...()`. Without one they refuse to run, so a
  missing condition never empties a table:
  `delete() needs a where(): ->where('id', $id)->delete(...). For every row of the table, write the SQL with Database::execute()`.
  `increment('stock', 5, ['restocked_at' => date('Y-m-d H:i:s')])` sets other columns at the same time.

### <a name="transactions"></a>Transactions

```php
$id = Database::transaction(function () use ($input) {
    // the book changes hands: close its open loan, then open the new one
    Database::table('loans')->where('book_id', $input['book_id'])->whereNull('returned_at')->update(['returned_at' => date('Y-m-d H:i:s')]);
    return Database::table('loans')->insert(['book_id' => $input['book_id'], 'borrower' => $input['borrower'], 'due_on' => $input['due_on']]);
});
```

All of it is saved, or none of it: an exception rolls everything back and is thrown again; otherwise
`transaction()` returns what the function returns. A transaction inside another one (or inside a test, which runs in
a transaction) is part of the outer one: catching its exception inside the outer one does not undo its rows. MySQL
saves a `CREATE` or an `ALTER` at once, which ends a transaction early: keep table changes in
[migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations).
## <a name="sql"></a>Under the hood: when to keep SQL

The builder writes one table's `SELECT` (with its relations), `INSERT`, `UPDATE` and `DELETE`. Keep SQL, with `?`
placeholders, for joins with `GROUP BY`, subqueries, database functions and changes to every row of a table:

```php
$rows = Database::execute('SELECT author_id, MAX(published_year) AS latest FROM books GROUP BY author_id HAVING latest > ?', [1970]);
// [['author_id' => 2, 'latest' => 1993], ['author_id' => 3, 'latest' => 1972]]
```

The model's own methods of before 2.19 keep working too: `(new Book('books'))->create($input)`,
`->update($changes, $id)`, `->delete($id)`, `$book->save()`
([Models: other ways](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models#querybuilder)). New code writes with
`Book::insert()`, `Book::where('id', $id)->update()` and `->delete()`.

`Query::useExecutor($object)` sends the builder's queries to another object with `execute($sql, $bindings)` (a test
double); `Query::useExecutor(null)` goes back to the database.
## <a name="models"></a>Common mistakes

+ **`Book::find()` with a `find()` of your own in the model** (G122): it fails. Leave it out, or `Book::query()->find(3)`.
+ **A table the class name does not give** (G123): `BookReview` reads `bookreviews`; declare
  `protected static $tableName = 'book_reviews';`.
+ **`Book::search(...)`**: not forwarded; write `Book::query()->search(...)`. And the model's own
  `(new Book('books'))->search('title', '%x%')` takes `%` as a wildcard, the builder's `search()` does not (G126).
+ **`paginate(20)` in a capability**: it reads the query string, which REST, agents and the command line do not send.
  Write `paginate(20, $input['page'] ?? 1)` with `'page' => 'integer'` in `$rules`.
+ **`update()` without `where()`** (G125): refused. `whereNotIn('id', [])` and `search($columns, '')` add no condition,
  so they do not count as one.
+ **Selected columns with models**: the other properties come back `null`; add `arrays()`.
+ **The N+1 warning in a worker** (G127): `APP_ENV` is read once per process, so a long worker counts across jobs;
  call `Query::watch(null)` between jobs.
## Related pages

+ [Relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships): `with()`, `withCount()`, pivots
+ [Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models): the tables and the models
+ [Build once](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP): capabilities on every channel
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#download): a list as a CSV file


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Filters-and-Order -->

The [query builder](https://github.com/caligrafy/caligrafy-quill/wiki/Queries) narrows the rows with `where()`,
`whereIn()`, `whereNull()`, `whereBetween()` and `search()`, picks the columns with `select()`, and sorts and limits
them with `orderBy()`, `latest()`, `limit()` and `offset()`. Every value is bound (sent apart from the SQL), and every
name is checked, so what a person types can never change the query. Since 2.19.0.

```php
Book::where('published_year', '<', 1975)->where('author_id', 1)->orderBy('title')->limit(10)->get();
```

The examples use the Bookshelf tables of [Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models).
## With Claude

Say what the list filters and sorts:

```text
/caligrafy-quill:new-capability list_books books:read read-only: the books sorted by title, 20 per page; filters author_id and search (title or summary)
```

Claude adds a `where()` per filter given and `search()` for words, each input declared in `$rules`.

**Check** before you say OK: no SQL string is built from an input, and `php caligrafer.php call list_books search=50%`
gives `"total": 0` (`%` is a character to find, not a wildcard).
## By hand

A query built step by step changes as you call it: `$query->where(...)` adds to `$query`. In a capability, add a
condition only for a filter that was given:

```php
public function handle(array $input, Context $context)
{
    $query = Book::with('author')->orderBy('title');
    if (!empty($input['author_id'])) {
        $query->where('author_id', $input['author_id']);
    }
    if (!empty($input['search'])) {
        $query->search(array('title', 'summary'), $input['search']);
    }
    return $query->paginate(20, $input['page'] ?? 1);
}
```

`toSql()` and `getBindings()` show the SQL and its values without running it:

```php
$query = Book::whereIn('id', [1, 2, 3])->whereNull('summary');
$query->toSql();        // SELECT * FROM `books` WHERE `id` IN (?, ?, ?) AND `summary` IS NULL
$query->getBindings();  // [1, 2, 3]
```
## <a name="where"></a>Reference: conditions

```php
Book::where('author_id', 1)->get();                               // author_id = 1
Book::where('published_year', '<', 1975)->where('author_id', 1)->get();   // AND
Book::where('published_year', '<', 1970)->orWhere('author_id', 3)->get(); // OR
Book::where(['author_id' => 1, 'published_year' => 1968])->get(); // several equalities, in parentheses
Book::where(function ($q) {                                       // a group in parentheses
    $q->where('published_year', '<', 1970)->orWhere('author_id', 3);
})->where('summary', '!=', null)->get();

Book::whereIn('id', [1, 2, 3])->get();                            // whereNotIn too
Book::whereNull('summary')->get();                                // whereNotNull too
Book::whereBetween('published_year', [1960, 1980])->get();        // both ends included
Book::query()->search(['title', 'summary'], $words)->get();       // title or summary contains the words
```

| Call | Meaning |
|---|---|
| [`where($column, $value)`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-where) | `=`; `where($column, null)` is `IS NULL` |
| `where($column, $operator, $value)` | operators `=`, `!=`, `<>`, `<`, `>`, `<=`, `>=`, `like`, `not like`; `where($column, '!=', null)` is `IS NOT NULL` |
| `where([$column => $value, ...])`, `where(function ($q) {...})` | equalities joined by `AND`, a group; both in parentheses |
| [`orWhere(...)`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-orwhere) | the same forms, joined by `OR` |
| [`whereIn($column, $list)`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-wherein), `whereNotIn($column, $list)` | an empty list: `whereIn` matches no row, `whereNotIn` adds no condition |
| `whereNull($column)`, `whereNotNull($column)` | `IS NULL`, `IS NOT NULL` |
| [`whereBetween($column, [$from, $to])`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-wherebetween) | both ends included |
| [`search($columns, $words)`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-search) | `(c1 LIKE ? OR c2 LIKE ?)` with `%words%` bound; `%` and `_` in the words are escaped; empty words add no condition |

| Query | SQL | Bindings |
|---|---|---|
| `Book::where(['author_id' => 1, 'published_year' => 1968])` | ``SELECT * FROM `books` WHERE (`author_id` = ? AND `published_year` = ?)`` | `[1, 1968]` |
| the group above | ``... WHERE (`published_year` < ? OR `author_id` = ?) AND `summary` IS NOT NULL`` | `[1970, 3]` |
| `Book::query()->search(['title', 'summary'], 'shadow 50%')` | ``... WHERE (`title` LIKE ? OR `summary` LIKE ?)`` | `['%shadow 50\%%', '%shadow 50\%%']` |
## <a name="order"></a>Reference: columns, order and limits

```php
Book::query()->latest()->limit(5)->offset(5)->get();              // newest first (created_at); oldest() the other way
Book::query()->select('id', 'title as name')->arrays()->get();    // two columns, renamed
```

| Call | Meaning |
|---|---|
| [`select(...$columns)`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-select) | `'id'`, `'books.*'`, `'title as name'`; one array works too |
| [`orderBy($column, 'asc' or 'desc')`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-orderby) | several calls sort by several columns |
| `latest($column = 'created_at')`, `oldest($column = 'created_at')` | newest or oldest first |
| `limit($n)`, `offset($n)` | whole numbers >= 0 |

``Book::query()->latest()->limit(5)->offset(5)`` writes ``SELECT * FROM `books` ORDER BY `created_at` DESC LIMIT 5 OFFSET 5``.

**Names are checked, values are bound.** A table or column name must be letters, digits and `_` (or `table.column`);
anything else is refused before any SQL runs: `[ERROR 2001] Invalid table or column name 'name; DROP': letters, digits
and _ only, with one optional prefix (table.column)`. Another operator gives `[ERROR 2001] Operator not allowed: use
=, !=, <>, <, >, <=, >=, like or not like`. A boolean is bound as `0`/`1`, a `DateTime` as `Y-m-d H:i:s`; an array
value is refused (use `whereIn`).
## Common mistakes

+ **`Book::search(...)`** is not forwarded to the builder: write `Book::query()->search(...)`. The model's own
  `(new Book('books'))->search('title', '%x%')` takes `%` as a wildcard; the builder's `search()` does not (G126).
+ **Selected columns with models**: `Book::query()->select('id', 'title')->get()` gives `Book` models whose other
  columns are `null`; add `arrays()` (G138).
+ **A filter read from `$input` that `$rules` does not declare**: only the inputs of `$rules` reach `handle()`.
## Related pages

+ [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries): the overview
+ [Getting the rows](https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Getting-Rows) · [Pagination](https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Pagination) · [Eager loading](https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Eager-Loading) · [Writing and transactions](https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Writing-and-Transactions)
+ [API: Caligrafy\Query](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Getting-Rows -->

A [query](https://github.com/caligrafy/caligrafy-quill/wiki/Queries) runs when you ask for its rows: `get()` for every
row, `first()` and `find()` for one, `value()` and `pluck()` for a value or a column, `count()` and `exists()` for a
number or a yes, `chunk()` for many rows in parts, `paginate()` for a page. What you get is **arrays** from
`Database::table()` and **models** from a model class. Since 2.19.0.

```php
use Caligrafy\Database;

$rows  = Database::table('books')->where('author_id', 2)->get();   // arrays
$book  = Book::find(3);                                            // a Book, or null
$count = Book::where('author_id', 2)->count();                     // 2
```
## With Claude

```text
/caligrafy-quill:new-capability get_book books:read read-only: one book by its id, not found when there is none
```

Claude reads the row with `Book::find($input['id'])` (or `with(...)->find(...)`) and throws
`ServiceError::notFound(...)` when it is `null`.

**Check:** `php caligrafer.php call get_book id=999` answers `not_found`, not an empty `data`.
## By hand

1. **Arrays or models.** `Database::table('books')` gives arrays, one per row. `Book::query()`, or a call of the query
   builder on the model class (`Book::where(...)`, `Book::find(3)`, `Book::with(...)`, `Book::first()`,
   `Book::paginate(20)`...), gives `Book` models, on the model's table: the class name in lower case plus `s`
   (`Book` -> `books`), unless the class declares `protected static $tableName = 'book_reviews';`.
2. **Switch between them.** `arrays()` keeps a model query's rows as arrays; `models(Book::class)` turns a
   `Database::table()` query's rows into models:
    ```php
    Book::query()->select('id', 'title')->arrays()->get();        // [['id' => 1, 'title' => 'A Wizard of Earthsea'], ...]
    Database::table('books')->models(Book::class)->get();         // Book models
    ```
3. **One row or nothing.** In a capability, a missing row is a refusal:
    ```php
    $book = Book::find($input['id']);
    if (!$book) {
        throw ServiceError::notFound('There is no book #' . $input['id']);
    }
    return $book;
    ```
## <a name="get"></a>Reference: getting the rows

| To get | Call | Returns |
|---|---|---|
| every row | [`get()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-get) | a list (empty when none) |
| the first row | [`first()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-first) | one row, or `null` |
| one row by id | [`find(3)`, `find($value, 'isbn')`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-find) | one row, or `null` |
| one value | [`value('title')`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-value) | `'Kindred'`, or `null` |
| one column | [`pluck('title')`, `pluck('title', 'id')`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-pluck) | `['A Wizard of Earthsea', ...]`, `[1 => 'A Wizard of Earthsea', ...]` |
| how many | [`count()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-count) | a number (order and limit ignored) |
| whether any | [`exists()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-exists) | `true` or `false` |
| a page | [`paginate(20, $page)`](https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Pagination) | `['data', 'total', 'page', 'per_page', 'pages']` |
| many rows, in parts | [`chunk(500, function ($rows, $part) { ... })`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-chunk) | `true`, or `false` when the function returned `false` |

+ `pluck()` also takes a count of `withCount()` or a relation of `with()`:
  `Author::withCount('books')->pluck('books_count', 'name')` gives `['Ursula K. Le Guin' => 2, ...]`.
+ `chunk()` reads in `id` order unless the query has an order; the function gets the rows and the number of the part
  (from 1), and returning `false` stops.
+ `count()`, `exists()`, `value()` and `pluck()` of a column run one small query, without the relations and without
  models.
## <a name="models"></a>Reference: models and arrays

| Query | Rows |
|---|---|
| `Database::table('books')` | arrays |
| `Book::query()`, `Book::where(...)`, `Book::find(3)` | `Book` models, related rows (`with()`) as arrays |
| `->arrays()` | arrays (undoes the models) |
| `->models(Book::class)` | instances of a class that extends `Caligrafy\Model` (another class is refused) |

A model has every property its class declares: with `select()`, the other columns are `null`, and a capability returns
them, `null`s included. For only the columns you selected, add `arrays()`.
## Common mistakes

+ **`Book::find()` with a `find()` of your own in the model** (G122): `Book::find(1)` then fails with "Non-static method
  cannot be called statically". Leave it out, or write `Book::query()->find(1)`.
+ **A table the class name does not give** (G123): `BookReview` reads `bookreviews`; declare
  `protected static $tableName = 'book_reviews';`.
+ **Selected columns with models** (G138): add `arrays()`.
+ **A query inside a `foreach`** over rows: load the related rows with
  [`with()`](https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Eager-Loading) instead.
## Related pages

+ [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries)
+ [Filters and order](https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Filters-and-Order) · [Pagination](https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Pagination) · [Eager loading](https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Eager-Loading) · [Writing and transactions](https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Writing-and-Transactions)
+ [Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models)
+ [API: Caligrafy\Query](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query) · [Caligrafy\Model](https://github.com/caligrafy/caligrafy-quill/wiki/API-Model)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Pagination -->

`paginate()` gives one page of a [query](https://github.com/caligrafy/caligrafy-quill/wiki/Queries)'s rows with the
numbers a page needs: the rows, how many there are in all, which page it is and how many pages there are. It runs two
queries (a count, then the page), and one when the page is past the last. A capability that returns a page serves it
the same way to web pages, REST, the JS client, agents and Snap's lists. Since 2.19.0.

```php
$page = Book::query()->orderBy('title')->paginate(2, 2);
// ['data' => [Kindred, Parable of the Sower], 'total' => 5, 'page' => 2, 'per_page' => 2, 'pages' => 3]
```
## With Claude

```text
/caligrafy-quill:new-capability list_books books:read read-only: the books sorted by title, 20 per page, with their author
```

Claude writes `paginate(20, $input['page'] ?? 1)` with `'page' => 'integer'` in `$rules`.

**Check** before you say OK: `php caligrafer.php call list_books page=2` gives `"page": 2` (and `"data": []` when there
are fewer than 21 books).
## By hand

1. **The capability** pages with the page of its input: REST, an agent and the command line have no query string.
    ```php
    public $rules = array('author_id' => 'integer', 'page' => 'integer');

    public $descriptions = array(
        'author_id' => 'Optional: only the books of this author',
        'page' => 'Optional: the page, 1 by default (20 books per page)'
    );

    public function handle(array $input, Context $context)
    {
        $query = Book::with('author')->orderBy('title');
        if (!empty($input['author_id'])) {
            $query->where('author_id', $input['author_id']);
        }
        return $query->paginate(20, $input['page'] ?? 1);
    }
    ```
2. **The page**, in `application/config/routing/web.php`: the query string reaches the capability as its inputs
   (`?page=2`, `?author_id=2`), and the `query` option gives the view `$author_id` to keep in the links:
    ```php
    Route::page('/books', 'Bookshelf/books', ['data' => ['books' => 'list_books', 'authors' => 'list_authors'], 'query' => ['author_id']]);
    ```
3. **The links**, in `application/views/Bookshelf/books.pug`
   ([the whole view](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views)):
    ```pug
    //- the next and previous pages keep the author of the address (?author_id=2)
    - $filter = $author_id !== '' ? '&author_id=' . (int) $author_id : '';
    p.cq-auth-note
        | Page #{$books['page']} of #{$books['pages']}, #{$books['total']} books
        if $books['page'] > 1
            |  · 
            a(href="{$home}books?page=" . ($books['page'] - 1) . $filter) Previous
        if $books['page'] < $books['pages']
            |  · 
            a(href="{$home}books?page=" . ($books['page'] + 1) . $filter) Next
    ```
   The rows are `$books['data']`. Pug in Caligrafy is PHP: strings join with `.`.
## <a name="reference"></a>Reference

[`paginate($perPage = 20, $page = null)`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-paginate)
returns:

| Key | What it is |
|---|---|
| `data` | the rows of the page (arrays or models, with their relations) |
| `total` | the rows of the whole query |
| `page` | the page number used |
| `per_page` | the rows per page |
| `pages` | the number of pages, at least 1 |

+ **Without a page number**, `paginate()` reads `page` from [`input($array)`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-input)
  when you gave one, else from the query string (`?page=2`).
+ A page number that is not a whole number >= 1 is page 1. A page past the last one gives `'data' => []` and runs no
  second query.
+ `$perPage` must be a whole number >= 1: anything else throws `paginate() needs a number of rows per page >= 1`.
+ Elsewhere a page keeps its shape: [`Route::download`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#download)
  exports the rows of that page only; a [Snap Show: List](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Show-Cards)
  shows its pages; a [card view](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Card-Views) gets `$rows` and
  `$page`.
## Common mistakes

+ **`paginate(20)` in a capability**: it reads the query string, which REST, agents and the command line do not send.
  Write `paginate(20, $input['page'] ?? 1)` with `'page' => 'integer'` in `$rules`.
+ **`page` missing from `$rules`**: undeclared inputs never reach `handle()`, so every page is page 1.
+ **Reading `$_GET` in the view**: the view gets the query string only through the `query` option of `Route::page`.
## Related pages

+ [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries#paging)
+ [Getting the rows](https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Getting-Rows)
+ [Views: a page of a list](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views)
+ [API: Query::paginate()](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-paginate)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Eager-Loading -->

**Eager loading** reads the related rows of a [query](https://github.com/caligrafy/caligrafy-quill/wiki/Queries) in
one more query per relation, instead of one query per row. Listing 50 books and then reading each one's author runs 51
queries (the N+1 problem); `with('author')` runs two: one for the books, one for all their authors
(`WHERE id IN (...)`). `withCount()` adds a count per row in one `GROUP BY` query. While you develop, Caligrafy warns
you when the same query runs 10 times in a request. Since 2.19.0.

**Since 2.26.0** a relation method called on one of several rows read by a query throws `[ERROR 2004] Lazy loading prevented` in development (a warning in production): load the relation with `with()` and read it as a property. `$book->lazy()->author()` or `#[Caligrafy\Lazy]` on the method allow a call that is meant; `STRICT_RELATIONS=false` makes it a warning.

```php
$books   = Book::with('author', ['tags' => ['pivot' => true]])->get();   // author: a row or null; tags: a list
$authors = Author::withCount('books')->get();                            // books_count on each
$loan    = Database::table('loans')->with('book.author')->first();       // the loan, its book, the book's author
```
## With Claude

```text
/caligrafy-quill:new-capability get_book books:read read-only: one book with its author, its loans and its tags
```

Claude reads the rows with `Book::with(...)`, and never queries in a loop.

**Check** before you say OK:
+ related rows come from `with()` or `withCount()`, not a query inside a `foreach`;
+ many-to-many relations say `['pivot' => true]` (or the pivot's name);
+ `php caligrafer.php call get_book id=3` shows the related rows under their names (`author`, `loans`, `tags`).
## By hand

1. **Name the relations.** `with()` follows the name you give and the table it is called on, so the models need no code:
    ```php
    $book = Book::with('author', 'loans', array('tags' => array('pivot' => true)))->find($input['id']);
    ```
   Four queries run: the book, then its author, its loans and its tags, each with `WHERE ... IN (...)`.
2. **Count instead of loading.**
    ```php
    return Author::withCount('books')->orderBy('name')->get();   // each author with books_count
    ```
3. **Narrow the related rows** with a function:
    ```php
    Book::with(['loans' => function ($q) { $q->whereNull('returned_at'); }])->get();
    ```
## <a name="names"></a>Reference: how `with()` reads a name

| Name | Called on | Kind | It reads | You get |
|---|---|---|---|---|
| `author` (singular) | `books` | belongs to | `books.author_id` -> `authors.id` | one row, or `null` |
| `books` (plural) | `authors` | has many | `books.author_id` = `authors.id` | a list, or `[]` |
| `['tags' => ['pivot' => true]]` | `books` | many to many | `books_tags.book_id` = `books.id`, `books_tags.tag_id` = `tags.id` | a list, or `[]` |
| `book.author` | `loans` | nested | `loans.book_id` -> `books.id`, then `books.author_id` -> `authors.id` | `book` with its `author` |
| `['current_loan' => ['type' => 'hasOne', 'table' => 'loans']]` | `books` | has one | `loans.book_id` = `books.id` | the first row, or `null` |

+ The related rows are **arrays**, also under models: `$book->author['name']`, `$book->tags[0]['name']`.
+ The key must be in the rows: `Book::select('id', 'title')->with('author')` has no `author_id`, so `author` is `null`.
+ The pivot of `books` and `tags` is `books_tags`; when it does not exist but `tags_books` does, `with()` uses that one.
+ Keys are read in chunks of 1000 (`Query::IN_CHUNK`); the main rows are never repeated by a join.
## <a name="settings"></a>Reference: the settings of a relation

```php
Book::with(['writer' => ['table' => 'authors', 'foreign_key' => 'author_id']])->find(3);   // $book->writer
Book::with(['current_loan' => ['type' => 'hasOne', 'table' => 'loans', 'query' => function ($q) { $q->whereNull('returned_at'); }]])->get();
```

| Setting | Meaning | Default |
|---|---|---|
| `type` | `belongsTo`, `hasOne`, `hasMany` or `belongsToMany` | singular name: `belongsTo`; plural: `hasMany`; with `pivot`: `belongsToMany` |
| `table` | the related table | the name in the plural (`belongsTo`, `hasOne`), the name itself (`hasMany`, `belongsToMany`) |
| `foreign_key` | belongs to: the column of this table; has one/many: the column of the related table; many to many: the pivot's column toward this table | `<name>_id` (belongs to), `<this table in the singular>_id` (the others) |
| `local_key` | the column of this table the others point at | `id` |
| `owner_key` | the column of the related table that is pointed at | `id` |
| `pivot` | `true` (the conventional pivot) or its name | none |
| `related_key` | the pivot's column toward the related table | `<name in the singular>_id` |
| `query` | a function that narrows the related rows | none |

An unknown setting, or a name that is not letters, digits and `_`, is refused before any query runs. All of it:
[Relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships#override).

### `withCount()`

```php
Database::table('tags')->withCount(['books' => ['pivot' => true]])->pluck('books_count', 'name');
Author::withCount(['books' => function ($q) { $q->where('published_year', '<', 1970); }])->pluck('books_count', 'name');
```

It counts plural relations only (has many, many to many): `withCount('author')` is refused. A row with nothing to count
gets `0`.
## <a name="nplusone"></a>Reference: the N+1 warning

While you develop (`APP_ENV` other than `production`), when the same `SELECT` shape runs 10 times in one request,
Caligrafy writes one line in the PHP error log, with the first file and line outside `framework/`:

```text
[Caligrafy] Probable N+1 query: the same SELECT ran 10 times in this request (select * from `books` where `id` = ? limit ?), from <the file>:<the line>. Load the rows once with with(): Database::table('books')->with('author')->get() or Book::with('author')->get().
```

+ It counts every query run through `Database::execute()`, models included. Production does not count.
+ `Query::$threshold` (10) is the count; `Query::$logger` (a callable) receives the line instead of `error_log()`;
  `Query::watch(true)` or `watch(false)` forces it on or off, `watch(null)` decides from `APP_ENV` again and forgets the
  shapes counted ([API](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-watch)).
## Common mistakes

+ **Relations follow names, not the database** (G124): irregular plurals (`person`/`people`) need `table` or `type`; a
  `limit()` in a `query` constraint limits the whole relation query, not each parent; a constraint on a many-to-many
  relation runs on the join: qualify columns (`tags.label`).
+ **`select()` without the key column**: the relation is `null`.
+ **The N+1 warning in a worker** (G127): `APP_ENV` is read once per process, so a long worker counts across jobs;
  call `Query::watch(null)` between jobs.
+ **A pivot inside `Database::transaction()` on PostgreSQL**: a failed query aborts the transaction; name the pivot
  (G124).
## Related pages

+ [Relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships): the conventions and the pivot
+ [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries#eager)
+ [Getting the rows](https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Getting-Rows)
+ [API: Query::with()](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-with) · [withCount()](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-withcount)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Writing-and-Transactions -->

The [query builder](https://github.com/caligrafy/caligrafy-quill/wiki/Queries) writes rows too: `insert()` one row or
many, `update()`, `delete()`, `increment()` and `decrement()` the rows a `where()` names, every value bound. A change
without a condition is refused, so a missing `where()` never empties a table. `Database::transaction()` saves several
changes together, or none of them. Since 2.19.0.

```php
$id = Database::table('tags')->insert(['name' => 'poetry']);                    // the new id, as a string: "4"
Database::table('tags')->where('id', $id)->update(['name' => 'poems']);         // 1: the rows changed
```
## With Claude

```text
/caligrafy-quill:new-capability lend_book books:write: lends a book to a borrower until a date; the open loan of the book, if any, is closed first
```

Claude writes the change with the query builder, in `Database::transaction()` when it takes several statements.

**Check** before you say OK:
+ every `update()` and `delete()` has a `where()`;
+ the changes that belong together are in one `Database::transaction()`;
+ no table change (`CREATE`, `ALTER`) runs inside it: those go in a [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations).
## By hand

1. **Write the rows** in a capability (not `readOnly`):
    ```php
    $id = Database::table('tags')->insert(['name' => 'poetry']);
    Database::table('tags')->insert([['name' => 'essay'], ['name' => 'travel']]);   // several rows, one statement

    Database::table('tags')->where('id', $id)->update(['name' => 'poems']);         // 1: the rows changed
    Book::where('id', 1)->increment('published_year');                              // also decrement('stock', 2)
    Database::table('tags')->whereIn('name', ['essay', 'travel', 'poems'])->delete(); // 3: the rows deleted
    ```
2. **Several changes together**:
    ```php
    $id = Database::transaction(function () use ($input) {
        // the book changes hands: close its open loan, then open the new one
        Database::table('loans')->where('book_id', $input['book_id'])->whereNull('returned_at')->update(['returned_at' => date('Y-m-d H:i:s')]);
        return Database::table('loans')->insert(['book_id' => $input['book_id'], 'borrower' => $input['borrower'], 'due_on' => $input['due_on']]);
    });
    ```
   All of it is saved, or none of it: an exception rolls everything back and is thrown again; otherwise `transaction()`
   returns what the function returns.
## <a name="write"></a>Reference: writing rows

| Call | Does | Returns |
|---|---|---|
| [`insert($row)`, `insert([$row, $row])`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-insert) | one `INSERT` for every row; the rows need the same columns | the last insert id |
| [`update($values)`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-update) | `UPDATE ... SET` the columns given, on the rows of the `where()` | the rows changed |
| [`delete()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-delete) | `DELETE` the rows of the `where()` | the rows deleted |
| [`increment($column, $amount = 1, $extra = [])`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query-increment), `decrement(...)` | `column = column + ?` (or `-`), and the `$extra` columns at the same time | the rows changed |

+ Arrays and objects are written as JSON, booleans as `0`/`1`.
+ `update()`, `delete()`, `increment()` and `decrement()` need a `where...()`. Without one they throw `LogicException`
  and run nothing:
  `delete() needs a where(): ->where('id', $id)->delete(...). For every row of the table, write the SQL with Database::execute()`.
+ `increment('stock', 5, ['restocked_at' => date('Y-m-d H:i:s')])` sets other columns at the same time; the amount must
  be a number.
+ `Book::insert([...])` writes on the model's table. New code writes with `Book::insert()`,
  `Book::where('id', $id)->update()` and `->delete()`; the model's own methods of before 2.19
  (`(new Book('books'))->create($input)`, `->update($changes, $id)`, `->delete($id)`) keep working.
## <a name="transactions"></a>Reference: transactions

[`Database::transaction(callable $callback)`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data#database-transaction):

+ committed when the function returns, rolled back when it throws (the exception is thrown again);
+ returns what the function returns;
+ a transaction inside another one (or inside a test, which runs in a transaction) just runs in the outer one:
  catching its exception inside the outer one does not undo its rows;
+ MySQL saves a `CREATE` or an `ALTER` at once, which ends a transaction early: keep table changes in migrations.

For what the builder does not write (joins with `GROUP BY`, subqueries, a change to every row), keep SQL with `?`
placeholders: `Database::execute($sql, $values)`
([when to keep SQL](https://github.com/caligrafy/caligrafy-quill/wiki/Queries#sql)).
## Common mistakes

+ **`update()` without `where()`** (G125): refused. `whereNotIn('id', [])` and `search($columns, '')` add no condition,
  so they do not count as one.
+ **Transactions do not nest** (G128): an inner exception you catch inside the outer callback does not undo the inner
  writes.
+ **`Model::belongsToMany()` inside a transaction**: its `CREATE TABLE IF NOT EXISTS` commits at once on MySQL (G128).
+ **`Database::execute()` with values pasted into the SQL** (G2): always `?` placeholders.
## Related pages

+ [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries#write)
+ [Migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations)
+ [Filters and order](https://github.com/caligrafy/caligrafy-quill/wiki/Query-Builder-Filters-and-Order)
+ [API: Caligrafy\Query](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query) · [Caligrafy\Database](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data#database)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication -->

Authentication lets people create an account, sign in and sign out, and keeps pages and capabilities for the people
allowed to use them. Caligrafy ships the parts: a `users` table, a `User` model, the sign-in and sign-up views, and one
line of `web.php`, `Route::auth()` (2.19.0), that declares the sign-in pages without a controller. Programs and AI
agents do not sign in: they use **personal access tokens**.

**Since 2.26.0**: passkeys need `php caligrafer.php add passkeys` once (`lbuchs/webauthn`); and a write capability declared without a `scope` needs, from a personal access token, the scope named after it or `*` (signed-in pages are unchanged): see [security defaults](https://github.com/caligrafy/caligrafy-quill/wiki/Security-Defaults).
## With Claude

Ask for sign-in in plain words. `/caligrafy-quill:idea` adds it to a new app unless everything is public, and
`/caligrafy-quill:new-capability` uses it for a capability that needs someone.

```text
/caligrafy-quill:new-capability Only signed-in people see /shelf, the list of books, and only administrators see /admin/shelf
```

Claude writes:

+ in `application/config/routing/web.php`: `Auth::authentication('User', 'users');`, then
  `Route::auth(['home' => '/shelf']);` and the pages with `'signedIn' => true` or `'level' => 1`;
+ runs `application/models/Auth/create_db.sql` (the `users` table);
+ a *Sign in* / *Create account* line for visitors and a *Sign out* link or button for signed-in people on the main page.

People sign in with a username by default. To sign in with an email, say so: *"people sign in with their email, kept in the
username column"* ([below](#emailsignin)).

Password reset and face sign-in are not in `Route::auth`: Claude leaves them out unless you ask. A password reset is
then two capabilities with `Route::page` and `Route::form` ([below](#passwordreset)), a face sign-in or a sign-in through
another site is a set of web-only capabilities with `Route::action` ([below](#betweensites)). Neither is a controller.

**Check**

+ A page that needs someone sends visitors to `/login`, and with `comeBack` brings them back after signing in.
+ *Create account*, then *Sign in*, lands on the `home` page; *Sign out* ends the session.
+ Five wrong passwords in a row for one username answer *Too many tries in a row. For your security, wait 15 minutes, then try again.*
+ `web.php` has no `AuthController` route uncommented next to `Route::auth` (one or the other, never both).
## By hand

These steps use the **Bookshelf** catalog of the course: its tables and sample books
(`application/models/Bookshelf/create_db.sql`, with the models `Book` and `Author`:
[lesson 03](https://github.com/caligrafy/caligrafy-quill-course/wiki/03-Your-Data)) and its capabilities `list_books`
and `create_book` (`application/services/Bookshelf/`:
[lessons 04](https://github.com/caligrafy/caligrafy-quill-course/wiki/04-Your-First-Capabilities) and
[05](https://github.com/caligrafy/caligrafy-quill-course/wiki/05-Rules-and-Changes)), in a project made with
the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart) and its Docker server
(`http://localhost:8080`). Without Docker, drop `docker compose exec dev-box` from the commands.

**1. Create the tables.** Run:

```bash
docker compose exec dev-box php caligrafer.php sql application/models/Auth/create_db.sql
docker compose exec dev-box php caligrafer.php sql application/models/Bookshelf/create_db.sql
```

Each prints ` application/models/<folder>/create_db.sql run on caligrafy`. The `users` script creates the table only when it
does not exist: running it again never deletes your users.

**2. Turn authentication on and declare the pages.** In `application/config/routing/web.php`, uncomment
`Auth::authentication('User', 'users');` and add the lines below it, so that the start of the `try` block reads:

```php
    // API ACCESS - add comments if you don't want to allow API access on routes
    Auth::activateAPI();

    // AUTHENTICATION
    Auth::authentication('User', 'users');
    Route::auth(['home' => '/shelf']);       // /login, /logout, /register, /notAuthorized

    // PAGES
    Route::page('/shelf', 'Bookshelf/shelf', ['signedIn' => true, 'comeBack' => true, 'data' => ['books' => 'list_books']]);
    Route::page('/admin/shelf', 'Bookshelf/shelf', ['level' => 1, 'data' => ['books' => 'list_books']]);

    // the REST API of the capabilities (step 7)
    Route::capabilities();
```

Leave the `AuthController` routes of the template commented: `Route::auth` replaces them.

**3. The page.** Write `application/views/Bookshelf/shelf.pug`:

```pug
extends ../default/master/site

block title
  | My shelf

block content
  main
    h1 My shelf
    p Signed in as #{$user['username']}.
    form(method='POST', action=$home . 'logout')
      =csrf()
      button(type='submit') Sign out
    ul
      each $book in $books['data']
        li= $book['title'] . ', ' . $book['author']['name']
```

`list_books` answers a page of books (`data`, `total`, `page`...), each with its `author`. Every `Route::page` view
also gets `$authorized` and `$user` (`id`, `username`, `permissions`). The *Sign out* button posts to `/logout` with
the form's CSRF token (2.19.1); a link, `a(href=$home . 'logout') Sign out`, signs out too (`GET /logout`).

**4. Try it.**

| You do | You get |
|---|---|
| Open `http://localhost:8080/shelf` | `302` to `/login?return=%2Fshelf` |
| *Create account*: `ada`, a password of 8 characters or more, twice | `302` to `/login`, *Your account is ready. Sign in to start.* |
| Sign in as `ada` from that page | `302` to `/shelf`: *Signed in as ada*, then *A Wizard of Earthsea, Ursula K. Le Guin* and the other books |
| Open `/admin/shelf` | `302` to `/notAuthorized`: *Restricted Page* (403) |
| *Sign out* | `302` to `/`; `/shelf` sends you to `/login` again |
| A wrong password, five times in a row | four times *We couldn't sign you in with those details. Check them and try again.* with the username kept in its field, then *Too many tries in a row. For your security, wait 15 minutes, then try again.* (429) |

The fifth failure locks that username from your address for 15 minutes, the right password included.
`docker compose exec dev-box php caligrafer.php cache clear` lifts the lock at once (the counts are in the cache).

**5. Make an administrator.** New accounts have `permissions` 0. In phpMyAdmin (`http://localhost:8077`), on the
database `caligrafy`, run:

```sql
UPDATE users SET permissions = 1 WHERE username = 'ada';
```

Open `/shelf`: you are sent to `/login`, because a session whose user changed in the database is no longer valid.
Sign in again: `/admin/shelf` opens.

**6. A token for a program.** A program that adds books has no account: give it a token. Run:

```bash
docker compose exec dev-box php caligrafer.php token create "Bookshelf importer" --scopes books:write --expires 30
```

It prints ` Token #1 "Bookshelf importer" created with books:write, expires <date>`, then the token, `cq_<id>_<secret>`,
shown only this once.

**7. Call a capability with it.**

```bash
curl -X POST -H "Authorization: Bearer cq_<id>_<secret>" -H "Content-Type: application/json" \
  -d '{"title": "The Dispossessed", "published_year": 1974, "author_id": 1}' \
  http://localhost:8080/capabilities/create_book
```

| You send | You get |
|---|---|
| the token | `201 {"data":{"id":6,"title":"The Dispossessed","published_year":1974,...}}` |
| a token made with `--scopes books:read` | `403 {"error":{"code":"forbidden","message":"This needs the scope books:write"}}` |
| no token (add `-H "Accept: application/json"`) | `401 {"error":{"code":"unauthenticated","message":"Sign in or send a personal access token"}}` |
| the token, with `"title": ""` | `422 {"error":{"code":"invalid",...,"fields":{"title":"The Title field is required"}}}` |
| the token after `php caligrafer.php token revoke 1` | `401` |

`docker compose exec dev-box php caligrafer.php audit` lists the calls and the refusals.

**Check**

+ `/shelf` sends visitors to `/login?return=%2Fshelf` and shows the books once signed in.
+ `/admin/shelf` answers *Restricted Page* to `permissions` 0 and opens for 1.
+ The fifth wrong password in a row is refused with 429.
+ The token adds a book, and a token without `books:write` cannot.
## <a name="routeauth"></a>Reference: `Route::auth`

`Route::auth(array $options = [])`, after `Auth::authentication('User', 'users')`, declares:

| Route | What it does |
|---|---|
| `GET /login` | the sign-in page (`Auth/login`); a signed-in person goes to `home`, or to `?return=` |
| `POST /login` | checks the identifier field and `passcode`; on success a new session id and a new CSRF token, then `home`, or the page of `/login?return=` |
| `GET /logout`, `POST /logout` | signs out (a new session id and CSRF token), then `logout` |
| `GET /notAuthorized` | the page of people below the level a page needs (403) |
| `GET /register`, `POST /register` | the sign-up page (`Auth/register`) and the `register_user` capability, then `/login` |
| `POST /passkey/register/options`, `/passkey/register`, `/passkey/login/options`, `/passkey/login` | with `'passkeys' => true` only |

| Option | Default | What it does |
|---|---|---|
| `home` | `'/'` | where people land once signed in, and where a signed-in person opening `/login` or `/register` goes |
| `logout` | `'/'` | where people land once signed out |
| `register` | `true` | `true` uses `register_user`; `false` declares no sign-up; a string names your own capability |
| `identifier` | `'username'` | the `users` column people sign in with, and the name of its form field (`'email'`...) |
| `signInAfterRegister` | `false` | `true` signs a new account in at once and sends it to `home` |
| `attemptsPerUser` | `0` (off) | failed sign-ins of one username, from any address, before it is locked for `lock` seconds (2.19.6): against guessing spread over many machines. It lets someone lock a known username out on purpose, so keep it high (20) |
| `level` | `0` | the lowest permission level (`permissions` column) that may sign in (2.19.5): `1` lets only administrators in; anyone below is refused exactly like a wrong password, and counted toward the lock |
| `messages` | the words above | what sign-in and sign-up say, in your own words: `invalid` and `locked` (a failed sign-in, 2.19.3; `{minutes}` is the wait), `mismatch`, `register_invalid`, `register_taken` and `registered` (the sign-up page, 2.19.4). Example: `['register_taken' => 'This email already has an account: sign in instead.']` |
| `attempts` | `5` | failed sign-ins allowed per username and address |
| `lock` | `900` | the window of those failures, in seconds |
| `views` | `['login' => 'Auth/login', 'register' => 'Auth/register']` | your own views |
| `prefix` | `''` | `'/account'` gives `/account/login`...; the shipped views post to `/login`, so write your own |
| `passkeys` | `false` | `true` adds the passkey endpoints ([passkeys](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition#passkeys); they need the `passkeys` table of the face login recipe) |

+ **Sign-in.** The user is found with the model's `findByUsername()` (for `username`), else its `findBy($column,
  $value)`, else a bound query on its table. The password is checked with `verifyPassword()`. A username that does not
  exist takes as long to refuse as one that does. A passcode stored by an old version (encrypted with the `APP_KEY`) is
  replaced by a hash at its next sign-in.
+ **Throttle.** Failures are counted per address (`REMOTE_ADDR`) and username, in the cache (`CACHE_STORE`; the session
  when the cache is off). Behind a proxy every visitor has the proxy's address: the limit is then per username. A wrong
  password answers the sign-in page again (`200`) with *We couldn't sign you in with those details. Check them and try again.* and what was typed in the username field (never the password); a locked one, `429`.
+ **Sign-up** sends the capability every field its `$rules` declare, nothing else. When the form has `confirmpasscode`,
  it must equal `passcode`. A refusal shows the page again with the field errors (`$errors`) and what was typed
  (`$user`), never the passwords. An existing username shows *An account already exists with these details. Sign in instead, or use other details.*, and inputs to fix *A few details need a fix: see the notes under the fields.*
+ **JSON.** A request with `Accept: application/json` gets JSON answers and must send the `X-CSRF-Token` header (else
  `403`): sign-in answers `200 {"data":{"user":{"id":1,"username":"ada","permissions":0}}}`, `401` (invalid) or `429`
  (locked); sign-out `200 {"data":{"signedOut":true}}`; sign-up `201 {"data": <the profile>}` or the capability's error.
+ **Coming back.** `/login?return=/books/3` (2.20.0) keeps that page in the session, and signing in goes there instead of
  `home`, with its query string. Only a path of this site is followed: `https://...`, `//...` or a backslash is ignored and
  the person goes to `home`. `Route::page` and `Route::action` with `'comeBack' => true` build the address.
+ **Not in `Route::auth`:** password reset (the `users` table has no email address: [below](#passwordreset)) and face
  sign-in (the [face login recipe](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition#face-login), web-only capabilities
  and tables of its own). `'reset' => true` or `'face' => true` stops with a `LogicException`.
+ **How the session signed in.** `Route::auth` records `password` or `passkey`: [`AuthRoutes::signedInBy()`](#signedinby) reads it (2.21.3).
+ More examples: [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#auth).

### Pages and capabilities that need someone

| Where | Setting | Who gets in | Others |
|---|---|---|---|
| `Route::page` | `'signedIn' => true` | anyone signed in | visitors: `302` to `/login` (`'comeBack' => true`: with `?return=`) |
| `Route::page`, `Route::form`, `Route::action` | `'visitorsOnly' => '/books'` | visitors | people signed in: `302` to that path |
| `Route::page` | `'level' => N` | signed in with `permissions >= N` | visitors: `/login`; below `N`: `/notAuthorized` |
| `#[Capability]` | `public: true` | everyone, visitors included | |
| `#[Capability]` | `level: N` (default `0`) | users with `permissions >= N`; tokens whose owner has it | `401` for visitors, `403` below the level |
| `#[Capability]` | `scope: 'books:read'` | tokens that grant the scope (`*` and `books:*` too) | `403` |

+ A signed-in user has every scope: for people only `level` counts.
+ A token created with `--user <id>` acts for that user: it needs the scope **and** the user's level. A token without
  an owner needs only the scope, whatever the level. A token whose owner was deleted is refused.
+ The command line (`php caligrafer.php call`), scheduled jobs, background jobs and webhooks have full access.
+ The level is compared with the `permissions` column (`Caligrafy\Context::$levelAttribute`).

### Helpers

| Function | What it does |
|---|---|
| `authorized()` | `true` when someone is signed in and their row in the database is unchanged |
| `user()` | the signed-in `User`, or `null` |
| `guard($attribute, $level, $loginUrl = '/login', $notAuthorizedUrl = '/notAuthorized')` | redirects and stops unless signed in with `$attribute >= $level` |
| `authorize($user)`, `unauthorize()` | signs a user in or out (no new session id: `Route::auth` does that) |
| `logout($url = '/')` | signs out, ends the session, redirects |

Each is also a static method of `Caligrafy\Auth` (`Auth::guard(...)`, `Auth::user()`). In a capability, read
`$context->user`, `$context->userId()` and `$context->level()` instead: a capability does not read the session. Only a
web-only capability (`webOnly: true`, served by `Route::action`) may.

### The `users` table and the `User` model

`application/models/Auth/create_db.sql` creates `users`: `id`, `username` (unique), `passcode` (`varchar(255)`),
`permissions` (0 by default), `created_at`, `modified_at`. `application/models/Auth/User.php` has:

```php
public function findByUsername($username);      // the User with exactly this username (bound query), or null
public function findBy($column, $value);        // the User whose column equals the value, or null
public static function hashPassword($password); // password_hash() of the password
public function verifyPassword($password);      // checks a password against the stored passcode
public function needsRehash();                  // true when the stored passcode must become a new hash
```

Passwords are stored with `password_hash()`: they cannot be read back, even with the `APP_KEY`. Accounts of older
versions, whose passcodes were encrypted with the `APP_KEY`, still sign in and get a hash then: keep the same
`APP_KEY` until they all signed in once.

### The views

| View | |
|---|---|
| `application/views/Auth/login.pug` | the sign-in form; its field is named after `$identifier` |
| `application/views/Auth/register.pug` | the sign-up form (`username`, `passcode`, `confirmpasscode`) |
| `application/views/Auth/users.pug`, `manageusers.pug` | the user administration pages of `AdminController` ([below](#adminpages)) |
| `application/views/default/index.pug` | the welcome page, with its signed-in and visitor states |

### <a name="usercapabilities"></a>User capabilities

The people who can sign in are managed by capabilities in `application/services/Users/`, like any other feature, so
the REST API and AI agents can manage them too:

| Capability | Who | What it does |
| --- | --- | --- |
| `list_users` | administrators | the users, newest change first: `id`, `username`, `permissions`, `created_at`, `modified_at` |
| `get_user` | administrators | one user (input `id`) |
| `update_user` | administrators | changes `username`, `passcode` (8 to 72 characters) or `permissions`; only the inputs given change |
| `delete_user` | administrators | deletes a user (`destructive`) and revokes their tokens |
| `register_user` | anyone, from the sign-up page or the command line | creates an account with `permissions` 0; refused over REST and MCP, so nobody can create accounts in bulk |

+ **Administrators** have `permissions >= CaligrafyUsers::ADMIN_LEVEL` (`1`, in
  `application/services/Users/CaligrafyUsers.php`): signed in, or calling with a token created for them (`--user`). The
  command line may always manage users; the legacy API key and a token without an owner never can.
+ **No one goes above their own level**: an administrator cannot change or delete someone whose `permissions` are
  higher than theirs (`403`), nor give more than their own (`422`), and cannot delete their own account.
+ **Never a password**: every answer leaves `passcode` out.
+ `register_user` accepts usernames of letters and digits (up to 100) and passwords of 8 to 72 characters.
+ The classes are `CaligrafyListUsers`, `CaligrafyGetUser`, `CaligrafyUpdateUser`, `CaligrafyDeleteUser`,
  `CaligrafyRegisterUser` and `CaligrafyUsers`: framework names that do not collide with yours.

### <a name="agents"></a>Users, tokens and agents

People sign in; programs and AI agents use personal access tokens.

```bash
php caligrafer.php token create <name> --scopes <a:read,b:write | *> [--user <id>] [--expires <days>]
php caligrafer.php token list
php caligrafer.php token revoke <id>
php caligrafer.php audit [--limit 50] [--capability <name>]
```

+ A token is `cq_<id>_<secret>`, shown once and stored as a hash in `caligrafy_tokens`, sent as
  `Authorization: Bearer cq_...`.
+ An agent that manages users needs a token of an administrator:
  `php caligrafer.php token create "Claude admin" --scopes users:read,users:write --user <their id>`, connected to
  `/mcp`. A token of someone who is not an administrator does not see these tools.
+ More in [Build once: tokens](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#tokens).
## <a name="signupform"></a>A sign-up page of your own

`/register` asks for a username and a password, and sends the person to `/login`. For a page that also asks to accept the
terms, signs in at once and is for visitors only, use `Route::form`, with the `register_user` capability
([the complete example](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form)):

```php
Route::page('/join', 'Bookshelf/join', ['visitorsOnly' => '/books']);
Route::form('/join', 'register_user', [
    'visitorsOnly' => '/books',
    'same' => ['confirmpasscode' => ['passcode', 'The two passwords are not the same']],
    'accepted' => ['terms' => 'Accept the terms of use to create an account'],
    'signsIn' => 'id',
    'success' => '/books',
    'back' => '/join',
]);
```
## <a name="passwordreset"></a>Password reset

The `users` table has no email address, so `Route::auth` has no password reset. It takes two capabilities and four routes,
and no controller. **With Claude:** "Add a password reset by email: a /forgot page, a link valid one hour that works once".

**1. The tables.** They hold data: add them with a [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations). Run
`docker compose exec dev-box php caligrafer.php migrate make add_password_resets`, and write in the file it names:

```sql
-- add_password_resets
ALTER TABLE users ADD COLUMN email VARCHAR(191) NULL, ADD UNIQUE KEY users_email_unique (email);

CREATE TABLE IF NOT EXISTS password_resets (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    user_id INT(15) NOT NULL,
    token_hash CHAR(64) NOT NULL,
    expires_at DATETIME NOT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uq_password_resets_token_hash (token_hash),
    CONSTRAINT fk_password_resets_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
```

Run `docker compose exec dev-box php caligrafer.php migrate`. People need an address in `users.email`: ask for it at
sign-up (`Route::auth`'s `register` option names your own capability) or on an account page. When the `username` column holds
the address ([Signing in with an email](#emailsignin)), leave out the `ALTER TABLE` statement and read
`->where('username', strtolower($input['email']))` in `request_password_reset` below.

**2. The capabilities.** `application/services/Account/RequestPasswordReset.php`:

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Database;
use Caligrafy\Mail;
use Caligrafy\Service;
use Caligrafy\ServiceError;
use Caligrafy\Throttle;

// request_password_reset: emails a link to choose a new password. The answer is the same whether the address exists or not
#[Capability(
    name: 'request_password_reset',
    description: 'Emails a link to choose a new password, valid one hour. Used by the page /forgot.',
    public: true,
    mcp: false
)]
class RequestPasswordReset extends Service
{
    // link and ip come from the route ('inputs'): the form cannot set them
    public $rules = array('email' => 'required|valid_email', 'link' => 'required', 'ip' => '');

    public function handle(array $input, Context $context)
    {
        if (!in_array($context->channel, array('web', 'cli'), true)) {
            throw ServiceError::forbidden('Ask for a new password on the page /forgot');
        }
        $throttle = new Throttle(5, 3600);
        $key = Throttle::key('password-reset', $input['ip'] ?? '', $input['email']);
        if (!$throttle->locked($key)) {
            $throttle->fail($key);
            $user = Database::table('users')->where('email', $input['email'])->first();
            if ($user) {
                $token = bin2hex(random_bytes(32));
                Database::table('password_resets')->where('user_id', $user['id'])->delete();
                Database::table('password_resets')->insert(array(
                    'user_id' => $user['id'],
                    'token_hash' => hash('sha256', $token),       // the database never holds the link
                    'expires_at' => gmdate('Y-m-d H:i:s', time() + 3600),
                ));
                (new Mail())->sendMail(
                    array('email' => $input['email']),
                    array(
                        'subject' => 'Choose a new password',
                        'body' => '<p><a href="' . htmlspecialchars($input['link'] . $token) . '">Choose a new password</a>. This link works once, for one hour.</p>',
                    ),
                    array('email' => getenv('MAIL_FROM') ?: getenv('MAIL_USERNAME'), 'name' => 'Bookshelf')
                );
            }
        }
        return array('sent' => true);
    }
}
```

`application/services/Account/ResetPassword.php`:

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Database;
use Caligrafy\Service;
use Caligrafy\ServiceError;

// reset_password: a valid link sets a new password, once
#[Capability(
    name: 'reset_password',
    description: 'Sets a new password from the link of a password reset email. The link works once, for one hour.',
    public: true,
    mcp: false
)]
class ResetPassword extends Service
{
    public $rules = array('token' => 'required|alpha_numeric|exact_len,64', 'passcode' => 'required|min_len,8|max_len,72');
    public $descriptions = array('token' => 'The token of the link', 'passcode' => 'The new password: 8 to 72 characters');

    public function handle(array $input, Context $context)
    {
        $reset = Database::table('password_resets')->where('token_hash', hash('sha256', $input['token']))->first();
        if (!$reset || $reset['expires_at'] < gmdate('Y-m-d H:i:s')) {
            throw ServiceError::invalid(array('token' => 'This link no longer works: ask for a new one'), 'This link no longer works: ask for a new one');
        }
        Database::table('users')->where('id', $reset['user_id'])->update(array('passcode' => User::hashPassword($input['passcode'])));
        Database::table('password_resets')->where('id', $reset['id'])->delete();
        return array('reset' => true);
    }
}
```

**3. The routes**, in `application/config/routing/web.php`, after `Route::auth(...)`:

```php
    Route::page('/forgot', 'Account/forgot', ['visitorsOnly' => '/books']);
    Route::form('/forgot', 'request_password_reset', [
        'inputs' => fn () => ['link' => session('home') . 'reset/', 'ip' => Caligrafy\AuthRoutes::ip()],
        'success' => '/forgot',
        'back' => '/forgot',
        'flash' => 'If this address has an account, a link is on its way. It works for one hour.',
    ]);
    Route::page('/reset/{token}', 'Account/reset', ['visitorsOnly' => '/books']);
    Route::form('/reset/{token}', 'reset_password', [
        'same' => ['passcode_again' => ['passcode', 'The two passwords are not the same']],
        'success' => '/login',
        'back' => '/reset/{token}',
        'flash' => 'Your password is changed. Sign in with it.',
    ]);
```

**4. The views.** `application/views/Account/forgot.pug`:

```pug
extends ../default/master/site

block content
  main.cq-auth
    h1 Forgot your password?
    if flash('success')
      .cq-alert.cq-alert--success(role='status')= flash('success')
    if flash('error')
      .cq-alert.cq-alert--error(role='alert')= flash('error')
    form(method='POST', action=$home . 'forgot')
      =csrf()
      .cq-field
        label(for='email') Your email address
        input#email.form-control(type='email', name='email', value=old('email'), required)
        if errors('email')
          p.cq-field-error= errors('email')
      button.btn.btn-primary(type='submit') Email me a link
```

`application/views/Account/reset.pug`:

```pug
extends ../default/master/site

block content
  main.cq-auth
    h1 Choose a new password
    if flash('error')
      .cq-alert.cq-alert--error(role='alert')= flash('error')
    form(method='POST', action=$home . 'reset/' . $token)
      =csrf()
      .cq-field
        label(for='passcode') New password
        input#passcode.form-control(type='password', name='passcode', required, autocomplete='new-password', maxlength='72')
        if errors('passcode')
          p.cq-field-error= errors('passcode')
      .cq-field
        label(for='passcode_again') The same password again
        input#passcode_again.form-control(type='password', name='passcode_again', required, autocomplete='new-password', maxlength='72')
        if errors('passcode_again')
          p.cq-field-error= errors('passcode_again')
      button.btn.btn-primary(type='submit') Save the new password
```

Add a link to `/forgot` in `application/views/Auth/login.pug`.

**5. Try it.** With `MAIL_HOST`, `MAIL_USERNAME`, `MAIL_PASSWORD` and `MAIL_FROM` in `.env`, the link arrives by email. To try
the page with no mail server, make a link by hand, in phpMyAdmin (`http://localhost:8077`):

```sql
INSERT INTO password_resets (user_id, token_hash, expires_at)
VALUES (1, SHA2(REPEAT('a', 64), 256), UTC_TIMESTAMP() + INTERVAL 1 HOUR);
```

Open `http://localhost:8080/reset/` followed by 64 times the letter `a`. Two different passwords come back with "The two
passwords are not the same"; two equal ones land on `/login` with "Your password is changed. Sign in with it.", and the
new password signs in. Open the link again and send it: "This link no longer works: ask for a new one".

**Check**

+ `/forgot` says the same for an address that exists and one that does not.
+ A `link` field added to the form changes nothing: `inputs` writes it.
+ The link works once. Changing the password also ends the person's open sessions (their row changed).
+ `php caligrafer.php capabilities` lists both, and neither is an MCP tool (`mcp: false`).
## <a name="betweensites"></a>A sign-in through another site

Signing in through another site (a partner, a company directory, OAuth) needs the session, sends the browser away and signs
someone in: two web-only capabilities and two [`Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#action) lines.
**With Claude:** "Add 'Sign in with Partner': the code comes back to /auth/partner".

`application/services/Account/PartnerSignIn.php` (`PARTNER_URL`, `PARTNER_CLIENT_ID` and `PARTNER_CLIENT_SECRET` in `.env`):

```php
<?php

use Caligrafy\AuthRoutes;
use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Database;
use Caligrafy\Service;
use Caligrafy\Web;

// GET /signin/partner: off to the other site, with a value only this browser knows
#[Capability(name: 'partner_sign_in', description: 'Sends the visitor to sign in on the partner site.', public: true, webOnly: true)]
class PartnerSignIn extends Service
{
    public function handle(array $input, Context $context)
    {
        $state = bin2hex(random_bytes(16));
        session('partner_state', $state);
        return Web::redirect(getenv('PARTNER_URL') . '/authorize?' . http_build_query(array(
            'client_id' => getenv('PARTNER_CLIENT_ID'),
            'redirect_uri' => session('home') . 'auth/partner',
            'state' => $state,
        )));
    }
}

// GET /auth/partner?code=&state=: back from the other site
#[Capability(name: 'partner_callback', description: 'Finishes a sign-in on the partner site.', public: true, webOnly: true)]
class PartnerCallback extends Service
{
    public $rules = array('code' => '', 'state' => '');

    public function handle(array $input, Context $context)
    {
        $expected = (string) session('partner_state');
        clearFromSession('partner_state');
        if ($expected === '' || !hash_equals($expected, (string) ($input['state'] ?? ''))) {
            return Web::redirect('/login');      // a sign-in that did not start in this browser
        }
        // the code is traded for the account, server to server, with the secret
        $answer = httpRequest(getenv('PARTNER_URL') . '/token', 'POST',
            array('code' => $input['code'] ?? '', 'client_secret' => getenv('PARTNER_CLIENT_SECRET')),
            array('Content-Type: application/json', 'Accept: application/json'));
        $username = 'partner' . preg_replace('/[^0-9]/', '', (string) ($answer['id'] ?? ''));
        if ($username === 'partner') {
            return Web::redirect('/login');
        }
        $users = new User('users');
        if (!$users->findByUsername($username)) {
            Database::table('users')->insert(array('username' => $username, 'passcode' => User::hashPassword(bin2hex(random_bytes(32)))));
        }
        AuthRoutes::signIn($users->findByUsername($username));
        return Web::redirect('/books');
    }
}
```

```php
    Route::action('/signin/partner', 'partner_sign_in');
    Route::action('/auth/partner', 'partner_callback');
```

`/signin/partner` answers `302` to the other site with a `state`. Back at `/auth/partner`, a wrong or missing `state` goes
to `/login`; the right one signs the person in and goes to `/books`. To remember how, for what only some sign-ins may do,
pass it as the third argument: `AuthRoutes::signIn($user, null, 'partner')`, then read it with `AuthRoutes::signedInBy()`
([above](#signedinby)). `AuthRoutes::signIn()` gives a new session id and a new
CSRF token. A page that stays open and keeps calling JSON uses `session_regenerate_id(true); Auth::authorize($user);`, as the
[face login recipe](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition#face-login) does, so its token stays valid.
## <a name="signedinby"></a>How a session signed in

Since 2.21.3, `AuthRoutes::signedInBy()` says how the current session signed in. `Route::auth` records `password` or
`passkey`. When you sign someone in yourself, say how:

```php
AuthRoutes::signIn($user, null, 'face');        // a new session id, a new CSRF token, and how it signed in
AuthRoutes::rememberSignIn('face');             // a page that stays open and signs in with Auth::authorize()
```

Use it for anything that changes how the account signs in. A face without a liveness check does not prove a person (a good
photo can pass), so a session opened that way must not be able to replace the face or add a passkey:

```php
if (AuthRoutes::signedInBy() !== 'password') {
    return Web::json(['error' => 'Sign in with your password to change your face'], 403);
}
```

It answers `null` when nobody is signed in or the sign-in was not recorded: treat that as not allowed. Signing out forgets it.

| Function of `Caligrafy\AuthRoutes` | What it does |
|---|---|
| `signIn($user, null, $how = null)` | a new session id, a new CSRF token, `Auth::authorize($user)`, and records `$how` |
| `rememberSignIn($how)` | records `$how`, for a page that signs in with `Auth::authorize()` (`null` forgets it) |
| `signedInBy()` | `password` or `passkey` through `Route::auth`, what you recorded otherwise, `null` when nobody recorded it or nobody is signed in |
| `signOut()` | `Auth::unauthorize()`, forgets `$how`, a new session id and CSRF token |

`Route::form` with `signsIn` records `password` (2.21.7); give another with `'signsInWith' => 'face'`.
## <a name="emailsignin"></a>Signing in with an email

`register_user` takes usernames of letters and digits. For people who sign in with their email address, the simplest way
keeps the `users` table: the `username` column holds the address, in lower case. `Route::auth`, passkeys, the throttle and
`$user['username']` keep working, with no new column. (A table with a separate `email` column: [other ways](#emailcolumn).)

**With Claude.** Say it in your idea or your request: *"people sign in with their email, kept in the username column"*.
`/caligrafy-quill:idea` puts it in the plan and writes the steps below.

**Check:** a sign-up with `Ada@Example.COM` lands in `users.username` as `ada@example.com`, and signing in as
`ADA@example.com` works.

**By hand**

**1. The column.** An address can be 254 characters. Before the table exists, write `username varchar(254) NOT NULL` in
`application/models/Auth/create_db.sql`. For a table that exists, run
`docker compose exec dev-box php caligrafer.php migrate make username_holds_email`, write in the file it names:

```sql
-- username_holds_email
ALTER TABLE users MODIFY username varchar(254) NOT NULL;
```

and run `docker compose exec dev-box php caligrafer.php migrate`.

**2. The rules.** In `application/services/Users/CaligrafyRegisterUser.php`, replace the `$rules` line with:

```php
public $rules = array('username' => 'required|valid_email|max_len,254', 'passcode' => 'required|min_len,8|max_len,72');
public $filters = array('username' => 'trim|lower_case');
```

and in `application/services/Users/CaligrafyUpdateUser.php` make the rule of `username` `'valid_email|max_len,254'` and add
`public $filters = array('username' => 'trim|lower_case');`. A later `update` keeps these two files and writes the
release's copies next to them as `.caligrafy-new`.

**3. The forms.** In `application/views/Auth/login.pug`, replace the `- $field`, `- $isEmail` lines and the `.cq-field` of the
identifier with:

```pug
        .cq-field
          label(for='username') Email
          input#username.form-control(type='email', name='username', value=isset($user) && is_object($user) ? ($user->username ?? '') : '', required, autocomplete='email', autocapitalize='none', maxlength='254')
```

In `application/views/Auth/register.pug`, change the `p.cq-lead` line to `p.cq-lead Your email address, and at least 8
characters for the password.` and the first `.cq-field` to:

```pug
      .cq-field
        label(for='username') Email
        input#username.form-control(type='email', name='username', value=$user->username?? '', required, autocomplete='email', autocapitalize='none', maxlength='254')
        if isset($errors['username'])
          p.cq-field-error= $errors['username']
```

The field stays named `username`. A sign-up page of your own ([above](#signupform)) changes the same way.

**4. The words.** Say it in the messages of `Route::auth`:

```php
Route::auth(['home' => '/books', 'messages' => [
    'invalid' => 'Invalid email or password',
    'register_taken' => 'An account already uses this email',
]]);
```

**5. Try it.**

| You do | You get |
|---|---|
| *Create account* with `not an email` | *A few details need a fix: see the notes under the fields.*, with the field's message under it |
| *Create account* with `Ada@Example.COM` | `302` to `/login`; `SELECT username FROM users` shows `ada@example.com` |
| The same address again | *An account already uses this email* |
| Sign in as `ADA@example.com` | `302` to `home`: the `username` column ignores case |
| A wrong password | *Invalid email or password* |

**Password reset** then needs no `email` column: see [Password reset](#passwordreset).
## <a name="otherways"></a>Other ways

### <a name="controller"></a>The authentication controller

Projects made before 2.19.0 declare the sign-in pages with `Caligrafy\Controllers\AuthController`
(`application/controllers/core/Auth/AuthController.php`). They keep working; use them or `Route::auth`, never both.

```php
Route::get('/home', 'Caligrafy\\Controllers\\AuthController@home');
Route::get('/login', 'Caligrafy\\Controllers\\AuthController');
Route::get('/logout', 'Caligrafy\\Controllers\\AuthController@logout');
Route::get('/notAuthorized', 'Caligrafy\\Controllers\\AuthController@notAuthorized');
Route::get('/register', 'Caligrafy\\Controllers\\AuthController@registerForm');
Route::post('/login', 'Caligrafy\\Controllers\\AuthController@login');
Route::post('/register', 'Caligrafy\\Controllers\\AuthController@register');
```

It signs in to `/home` and has neither the throttle, nor the new session id, nor the `?return=` of `Route::auth`. A
controller you keep signs a user in with `authorize($user)`: call `session_regenerate_id(true)` just before it.

### <a name="adminpages"></a>The user administration pages

`AdminController` serves pages that list, edit and delete users, through the user capabilities above, for
`permissions >= 1`. The template's lines still name it, and it works:

```php
Route::get('/admin', 'Caligrafy\\Controllers\\AdminController');
Route::get('/users', 'Caligrafy\\Controllers\\AdminController');
Route::get('/users/{id}/edit', 'Caligrafy\\Controllers\\AdminController@editUserForm');
Route::put('/users/{id}/edit', 'Caligrafy\\Controllers\\AdminController@updateUser');
Route::delete('/users/{id}/edit', 'Caligrafy\\Controllers\\AdminController@deleteUser');
```

To declare them instead, give the capabilities' answers to views of your own (the shipped ones expect the objects
`AdminController` passes):

```php
Route::page('/users', 'Admin/users', ['level' => CaligrafyUsers::ADMIN_LEVEL, 'data' => ['people' => 'list_users']]);
Route::page('/users/{id}/edit', 'Admin/person', ['level' => CaligrafyUsers::ADMIN_LEVEL, 'data' => ['person' => 'get_user'], 'notFound' => 'Admin/missing']);
Route::form('/users/{id}/edit', 'update_user', ['method' => 'PUT', 'success' => '/users', 'back' => '/users/{id}/edit']);
Route::form('/users/{id}/edit', 'delete_user', ['method' => 'DELETE', 'success' => '/users']);
```

Short names (`'AuthController@login'`) keep working: a short name that is not a class of yours falls back to
`Caligrafy\Controllers`.

### <a name="emailcolumn"></a>A separate `email` column

[Signing in with an email](#emailsignin) keeps the address in `username`, and is the simplest. When you need both a username
and an address, `Route::auth(['identifier' => 'email'])` signs in with the `email` column, and the shipped `login.pug` names its
field after `$identifier`. The shipped `users` table has no `email` column and `register_user` asks for a username: add the
column in a migration and write your own sign-up capability (`'register' => 'register_reader'`) whose `$rules` declare
`email`.
## Common mistakes

+ **A sign-out form answers `[ERROR 3000]` (403) before 2.19.1.** In 2.19.0 a `POST /logout` sent by a form signed out,
  then failed its CSRF check against the new token. Since 2.19.1 the form works (`form(method='POST', action=$home .
  'logout')` with `=csrf()`); on 2.19.0, sign out with a link, `a(href=$home . 'logout') Sign out`.
+ **Promoted, then sent to `/login`.** Changing a user's row (their `permissions`) ends their session: they sign in again.
+ **`Route::auth needs Auth::authentication('User', 'users') in web.php`.** Uncomment that line above `Route::auth`.
+ **Usernames with `@` or spaces are refused** at sign-up (`alpha_numeric`): say so next to the form, or
  [sign in with an email](#emailsignin).
+ **A `prefix` with the shipped views.** They post to `/login` and link to `/register`: with a prefix, write your own.
+ **A JSON sign-in answers 403.** Send the `X-CSRF-Token` header with the session's token.
+ **Locked out while testing.** `php caligrafer.php cache clear` empties the failure counts.
+ **A view without `$user`.** A closure that returns `view()` does not get `$authorized` and `$user`: use `Route::page`,
  or `Web::view()` in a web-only capability.
+ **A `return=` that goes nowhere.** Only a path of this site is followed: `/books/3`, never `https://...` or `//...`.
## Related pages

+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#auth)
+ [Build once: services, capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP)
+ [Face detection, face login and passkeys](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition)
+ [Security and upgrading](https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading)

<br /><br />
>[Next Section: Learn about Payments with Stripe](https://github.com/caligrafy/caligrafy-quill/wiki/9.2-Stripe-&-Cryptocurrency-Payment)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Sign-In-with-an-Email -->

How to let people **sign in with their email address**. The simplest way keeps the `users` table as it is: the
`username` column holds the address, in lower case. `Route::auth`, passkeys, the throttle and `$user['username']` keep
working, with no new column. It takes a wider column, two rules, two form fields and two messages. Since 2.19.0.
## With Claude

Say it in your idea or your request:

```text
"people sign in with their email, kept in the username column"
```

`/caligrafy-quill:idea` puts it in the plan and writes the steps below.

**Check:** a sign-up with `Ada@Example.COM` lands in `users.username` as `ada@example.com`, and signing in as
`ADA@example.com` works.
## By hand

1. **The column.** An address can be 254 characters. Before the table exists, write `username varchar(254) NOT NULL` in
   `application/models/Auth/create_db.sql`. For a table that exists, run
   `docker compose exec dev-box php caligrafer.php migrate make username_holds_email`, write in the file it names:
    ```sql
    -- username_holds_email
    ALTER TABLE users MODIFY username varchar(254) NOT NULL;
    ```
   and run `docker compose exec dev-box php caligrafer.php migrate`.
2. **The rules.** In `application/services/Users/CaligrafyRegisterUser.php`, replace the `$rules` line with:
    ```php
    public $rules = array('username' => 'required|valid_email|max_len,254', 'passcode' => 'required|min_len,8|max_len,72');
    public $filters = array('username' => 'trim|lower_case');
    ```
   and in `application/services/Users/CaligrafyUpdateUser.php` make the rule of `username` `'valid_email|max_len,254'`
   and add `public $filters = array('username' => 'trim|lower_case');`. A later `update` keeps these two files and writes
   the release's copies next to them as `.caligrafy-new`.
3. **The forms.** In `application/views/Auth/login.pug`, replace the `- $field`, `- $isEmail` lines and the `.cq-field`
   of the identifier with:
    ```pug
            .cq-field
              label(for='username') Email
              input#username.form-control(type='email', name='username', value=isset($user) && is_object($user) ? ($user->username ?? '') : '', required, autocomplete='email', autocapitalize='none', maxlength='254')
    ```
   In `application/views/Auth/register.pug`, change the `p.cq-lead` line to
   `p.cq-lead Your email address, and at least 8 characters for the password.` and the first `.cq-field` to:
    ```pug
          .cq-field
            label(for='username') Email
            input#username.form-control(type='email', name='username', value=$user->username?? '', required, autocomplete='email', autocapitalize='none', maxlength='254')
            if isset($errors['username'])
              p.cq-field-error= $errors['username']
    ```
   The field stays named `username`. A [sign-up page of your own](https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Build-a-Sign-Up-Page)
   changes the same way.
4. **The words**, in the messages of `Route::auth`:
    ```php
    Route::auth(['home' => '/books', 'messages' => [
        'invalid' => 'Invalid email or password',
        'register_taken' => 'An account already uses this email',
    ]]);
    ```
5. **Try it.**

| You do | You get |
|---|---|
| *Create account* with `not an email` | *A few details need a fix: see the notes under the fields.*, with the field's message under it |
| *Create account* with `Ada@Example.COM` | `302` to `/login`; `SELECT username FROM users` shows `ada@example.com` |
| The same address again | *An account already uses this email* |
| Sign in as `ADA@example.com` | `302` to `home`: the `username` column ignores case |
| A wrong password | *Invalid email or password* |
## <a name="column"></a>Another way: a separate `email` column

When you need both a username and an address, `Route::auth(['identifier' => 'email'])` signs in with the `email` column,
and the shipped `login.pug` names its field after `$identifier`. The shipped `users` table has no `email` column and
`register_user` asks for a username: add the column in a [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations)
and write your own sign-up capability (`'register' => 'register_reader'`) whose `$rules` declare `email`. The lookup is
the model's `findBy($column, $value)` (the shipped `User` has it), else a bound query on its table.
## Common mistakes

+ **`'identifier' => 'email'` with the shipped views and table** (G133): the POST field is named after the identifier, so
  a `username` field no longer signs in; and the table needs an `email` column.
+ **The sign-up refuses an address** (G75): the shipped `register_user` accepts letters and digits only, until its rules
  change as in step 2.
+ **A mixed-case address in the table**: the `lower_case` filter keeps them all in lower case.
## Related pages

+ [Sign-in, users and tokens](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#emailsignin)
+ [How to reset a password](https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Reset-a-Password): with the address in `username`, no new column
+ [Migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations)
+ [API: Caligrafy\AuthRoutes](https://github.com/caligrafy/caligrafy-quill/wiki/API-AuthRoutes)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Reset-a-Password -->

How to add a **password reset by email**: a `/forgot` page that emails a link, valid one hour, that works once, and a
`/reset/{token}` page that sets the new password. `Route::auth` has no password reset (the shipped `users` table has no
email address), so it takes two capabilities, four routes and two views, and no controller. The database never holds
the link: only its SHA-256 hash. Since 2.19.0.
## With Claude

```text
"Add a password reset by email: a /forgot page, a link valid one hour that works once"
```

**Check**

+ `/forgot` says the same for an address that exists and one that does not.
+ The link works once, for one hour.
## By hand

**1. The tables.** They hold data: add them with a [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations). Run
`docker compose exec dev-box php caligrafer.php migrate make add_password_resets`, and write in the file it names:

```sql
-- add_password_resets
ALTER TABLE users ADD COLUMN email VARCHAR(191) NULL, ADD UNIQUE KEY users_email_unique (email);

CREATE TABLE IF NOT EXISTS password_resets (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    user_id INT(15) NOT NULL,
    token_hash CHAR(64) NOT NULL,
    expires_at DATETIME NOT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uq_password_resets_token_hash (token_hash),
    CONSTRAINT fk_password_resets_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
```

Run `docker compose exec dev-box php caligrafer.php migrate`. People need an address in `users.email`: ask for it at
sign-up (`Route::auth`'s `register` option names your own capability) or on an account page. When the `username` column holds
the address ([Signing in with an email](https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Sign-In-with-an-Email)), leave out the `ALTER TABLE` statement and read
`->where('username', strtolower($input['email']))` in `request_password_reset` below.

**2. The capabilities.** `application/services/Account/RequestPasswordReset.php`:

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Database;
use Caligrafy\Mail;
use Caligrafy\Service;
use Caligrafy\ServiceError;
use Caligrafy\Throttle;

// request_password_reset: emails a link to choose a new password. The answer is the same whether the address exists or not
#[Capability(
    name: 'request_password_reset',
    description: 'Emails a link to choose a new password, valid one hour. Used by the page /forgot.',
    public: true,
    mcp: false
)]
class RequestPasswordReset extends Service
{
    // link and ip come from the route ('inputs'): the form cannot set them
    public $rules = array('email' => 'required|valid_email', 'link' => 'required', 'ip' => '');

    public function handle(array $input, Context $context)
    {
        if (!in_array($context->channel, array('web', 'cli'), true)) {
            throw ServiceError::forbidden('Ask for a new password on the page /forgot');
        }
        $throttle = new Throttle(5, 3600);
        $key = Throttle::key('password-reset', $input['ip'] ?? '', $input['email']);
        if (!$throttle->locked($key)) {
            $throttle->fail($key);
            $user = Database::table('users')->where('email', $input['email'])->first();
            if ($user) {
                $token = bin2hex(random_bytes(32));
                Database::table('password_resets')->where('user_id', $user['id'])->delete();
                Database::table('password_resets')->insert(array(
                    'user_id' => $user['id'],
                    'token_hash' => hash('sha256', $token),       // the database never holds the link
                    'expires_at' => gmdate('Y-m-d H:i:s', time() + 3600),
                ));
                (new Mail())->sendMail(
                    array('email' => $input['email']),
                    array(
                        'subject' => 'Choose a new password',
                        'body' => '<p><a href="' . htmlspecialchars($input['link'] . $token) . '">Choose a new password</a>. This link works once, for one hour.</p>',
                    ),
                    array('email' => getenv('MAIL_FROM') ?: getenv('MAIL_USERNAME'), 'name' => 'Bookshelf')
                );
            }
        }
        return array('sent' => true);
    }
}
```

`application/services/Account/ResetPassword.php`:

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Database;
use Caligrafy\Service;
use Caligrafy\ServiceError;

// reset_password: a valid link sets a new password, once
#[Capability(
    name: 'reset_password',
    description: 'Sets a new password from the link of a password reset email. The link works once, for one hour.',
    public: true,
    mcp: false
)]
class ResetPassword extends Service
{
    public $rules = array('token' => 'required|alpha_numeric|exact_len,64', 'passcode' => 'required|min_len,8|max_len,72');
    public $descriptions = array('token' => 'The token of the link', 'passcode' => 'The new password: 8 to 72 characters');

    public function handle(array $input, Context $context)
    {
        $reset = Database::table('password_resets')->where('token_hash', hash('sha256', $input['token']))->first();
        if (!$reset || $reset['expires_at'] < gmdate('Y-m-d H:i:s')) {
            throw ServiceError::invalid(array('token' => 'This link no longer works: ask for a new one'), 'This link no longer works: ask for a new one');
        }
        Database::table('users')->where('id', $reset['user_id'])->update(array('passcode' => User::hashPassword($input['passcode'])));
        Database::table('password_resets')->where('id', $reset['id'])->delete();
        return array('reset' => true);
    }
}
```

**3. The routes**, in `application/config/routing/web.php`, after `Route::auth(...)`:

```php
    Route::page('/forgot', 'Account/forgot', ['visitorsOnly' => '/books']);
    Route::form('/forgot', 'request_password_reset', [
        'inputs' => fn () => ['link' => session('home') . 'reset/', 'ip' => Caligrafy\AuthRoutes::ip()],
        'success' => '/forgot',
        'back' => '/forgot',
        'flash' => 'If this address has an account, a link is on its way. It works for one hour.',
    ]);
    Route::page('/reset/{token}', 'Account/reset', ['visitorsOnly' => '/books']);
    Route::form('/reset/{token}', 'reset_password', [
        'same' => ['passcode_again' => ['passcode', 'The two passwords are not the same']],
        'success' => '/login',
        'back' => '/reset/{token}',
        'flash' => 'Your password is changed. Sign in with it.',
    ]);
```

**4. The views.** `application/views/Account/forgot.pug`:

```pug
extends ../default/master/site

block content
  main.cq-auth
    h1 Forgot your password?
    if flash('success')
      .cq-alert.cq-alert--success(role='status')= flash('success')
    if flash('error')
      .cq-alert.cq-alert--error(role='alert')= flash('error')
    form(method='POST', action=$home . 'forgot')
      =csrf()
      .cq-field
        label(for='email') Your email address
        input#email.form-control(type='email', name='email', value=old('email'), required)
        if errors('email')
          p.cq-field-error= errors('email')
      button.btn.btn-primary(type='submit') Email me a link
```

`application/views/Account/reset.pug`:

```pug
extends ../default/master/site

block content
  main.cq-auth
    h1 Choose a new password
    if flash('error')
      .cq-alert.cq-alert--error(role='alert')= flash('error')
    form(method='POST', action=$home . 'reset/' . $token)
      =csrf()
      .cq-field
        label(for='passcode') New password
        input#passcode.form-control(type='password', name='passcode', required, autocomplete='new-password', maxlength='72')
        if errors('passcode')
          p.cq-field-error= errors('passcode')
      .cq-field
        label(for='passcode_again') The same password again
        input#passcode_again.form-control(type='password', name='passcode_again', required, autocomplete='new-password', maxlength='72')
        if errors('passcode_again')
          p.cq-field-error= errors('passcode_again')
      button.btn.btn-primary(type='submit') Save the new password
```

Add a link to `/forgot` in `application/views/Auth/login.pug`.

**5. Try it.** With `MAIL_HOST`, `MAIL_USERNAME`, `MAIL_PASSWORD` and `MAIL_FROM` in `.env`, the link arrives by email. To try
the page with no mail server, make a link by hand, in phpMyAdmin (`http://localhost:8077`):

```sql
INSERT INTO password_resets (user_id, token_hash, expires_at)
VALUES (1, SHA2(REPEAT('a', 64), 256), UTC_TIMESTAMP() + INTERVAL 1 HOUR);
```

Open `http://localhost:8080/reset/` followed by 64 times the letter `a`. Two different passwords come back with "The two
passwords are not the same"; two equal ones land on `/login` with "Your password is changed. Sign in with it.", and the
new password signs in. Open the link again and send it: "This link no longer works: ask for a new one".

**Check**

+ `/forgot` says the same for an address that exists and one that does not.
+ A `link` field added to the form changes nothing: `inputs` writes it.
+ The link works once. Changing the password also ends the person's open sessions (their row changed).
+ `php caligrafer.php capabilities` lists both, and neither is an MCP tool (`mcp: false`).
## <a name="reference"></a>Reference

| Piece | Why |
|---|---|
| `new Throttle(5, 3600)`, `Throttle::key('password-reset', $ip, $email)` | 5 requests an hour per address and email, then nothing more is sent ([API](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#throttle)) |
| the same answer whether the address exists or not | nobody learns which addresses have an account |
| `hash('sha256', $token)` | the database never holds the link |
| `'inputs' => fn () => [...]` | `link` and `ip` come from the server; a field the form adds is replaced ([`Route::form`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form)) |
| `$context->channel` web or cli, `mcp: false` | the reset is asked for on the page, never by an agent |
| `User::hashPassword()` | the new password is stored with `password_hash()` |
| `same` | the two passwords must match before the capability runs |

`AuthRoutes::ip()` is the visitor's address ([API](https://github.com/caligrafy/caligrafy-quill/wiki/API-AuthRoutes#authroutes-ip)).
## Common mistakes

+ **The email never arrives**: `MAIL_HOST`, `MAIL_USERNAME`, `MAIL_PASSWORD` and `MAIL_FROM` must be in `.env`.
+ **A `link` field in the form**: it changes nothing, `inputs` writes it; never build the link from what the form sent.
+ **The flash message is gone** (G129): it lasts one request; `success` and `back` must be the pages that show it.
+ **The tables in `create_db.sql` of an app that runs**: add them with a migration, which runs once (G120).
## Related pages

+ [Sign-in, users and tokens](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#passwordreset)
+ [How to sign in with an email](https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Sign-In-with-an-Email)
+ [Declarative routes: `Route::form`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form)
+ [Migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Build-a-Sign-Up-Page -->

How to build a **sign-up page of your own**: a page for visitors only that asks for a username and a password typed
twice, asks to accept the terms, creates the account with the `register_user` capability the authentication module
ships, and signs the person in at once. One `Route::page`, one `Route::form` and a Pug view: no controller. Since
2.20.0 (`same`, `accepted`, `signsIn`, `visitorsOnly`).

`/register` of [`Route::auth`](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#routeauth) already
asks for a username and a password and sends the person to `/login`; this page is for when you want more.
## With Claude

```text
"A sign-up page at /join with the password typed twice and a terms box; it signs people in and sends them to /books"
```

Claude writes the two routes and the view below.

**Check**

+ `/join` sends someone already signed in to `/books`.
+ Two different passwords and an empty box come back with a message under each, and the username stays.
+ A right form lands on `/books`, signed in.
## By hand

Before you start: the authentication module (`Auth::authentication('User', 'users');` and `Route::auth(...)` in
`web.php`).

1. **The routes**, in `application/config/routing/web.php`, after `Route::auth(...)`:
    ```php
    Route::page('/join', 'Bookshelf/join', ['visitorsOnly' => '/books']);
    Route::form('/join', 'register_user', [
        'visitorsOnly' => '/books',
        'same' => ['confirmpasscode' => ['passcode', 'The two passwords are not the same']],
        'accepted' => ['terms' => 'Accept the terms of use to create an account'],
        'signsIn' => 'id',
        'success' => '/books',
        'back' => '/join',
        'flash' => 'Welcome to the Bookshelf',
    ]);
    ```
   `register_user` answers the new account, and `'signsIn' => 'id'` signs in the person whose id is in that field (a new
   session id and a new CSRF token, as for `Route::auth`).
2. **The view**, `application/views/Bookshelf/join.pug`:
    ```pug
    extends ../default/master/site

    block content
      main.cq-auth
        h1 Join the Bookshelf
        if flash('error')
          .cq-alert.cq-alert--error(role='alert')= flash('error')
        form(method='POST', action=$home . 'join')
          =csrf()
          .cq-field
            label(for='username') Username
            input#username.form-control(type='text', name='username', value=old('username'), required)
            if errors('username')
              p.cq-field-error= errors('username')
          .cq-field
            label(for='passcode') Password
            input#passcode.form-control(type='password', name='passcode', required, autocomplete='new-password', maxlength='72')
            if errors('passcode')
              p.cq-field-error= errors('passcode')
          .cq-field
            label(for='confirmpasscode') The same password again
            input#confirmpasscode.form-control(type='password', name='confirmpasscode', required, autocomplete='new-password', maxlength='72')
            if errors('confirmpasscode')
              p.cq-field-error= errors('confirmpasscode')
          .cq-field
            label
              input(type='checkbox', name='terms', value='1')
              |  I accept the terms of use
            if errors('terms')
              p.cq-field-error= errors('terms')
          button.btn.btn-primary(type='submit') Join
    ```
3. **Try it.** Sign out and open `http://localhost:8080/join`. Send two different passwords and leave the box empty: the
   page comes back with "Some of the inputs are invalid", "The two passwords are not the same" under the second password
   and "Accept the terms of use to create an account" under the box, and the username is still there. Send the form
   right: you land on `/books`, signed in, with "Welcome to the Bookshelf" (when `books.pug` shows `flash('success')`).
   Open `/join` again: you are sent to `/books`.
## <a name="reference"></a>Reference

| Option of `Route::form` | Here |
|---|---|
| `visitorsOnly` | people already signed in go to `/books`, and the capability does not run |
| `same` | `confirmpasscode` must equal `passcode`; checked before the capability, its message in `errors('confirmpasscode')` |
| `accepted` | the box `terms` must be ticked |
| `signsIn` | the field of the answer that holds the id of the person to sign in; `signsInWith` says how (`'password'` by default, for `AuthRoutes::signedInBy()`) |
| `success`, `back`, `flash` | where a good form and a refused one go, and the message |

The checks run in this order: `visitorsOnly`, then (JSON with the session) the CSRF header, then `same` and `accepted`,
then the capability. All the options: [Declarative routes: `Route::form`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form).

`register_user` accepts usernames of letters and digits (up to 100) and passwords of 8 to 72 characters, gives
`permissions` 0, and is refused over REST and MCP, so nobody can create accounts in bulk.
## Common mistakes

+ **A username with a dot or an `@`** is refused: `register_user` takes letters and digits (G75). For an email, see
  [How to sign in with an email](https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Sign-In-with-an-Email).
+ **The messages are gone on the next page** (G129): they last one request; `back` and `success` must be the pages that
  show them.
+ **Declaring `confirmpasscode` in `$rules`**: `same` reads it from what was sent; declare it only if the capability
  needs it.
+ **A field `register_user`'s `$rules` do not list** never reaches it (G133).
## Related pages

+ [Sign-in, users and tokens](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#signupform)
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#form)
+ [How to sign in with an email](https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Sign-In-with-an-Email)
+ [API: Caligrafy\Form](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#form) · [Caligrafy\AuthRoutes](https://github.com/caligrafy/caligrafy-quill/wiki/API-AuthRoutes)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Sign-In-Through-Another-Site -->

How to let people **sign in through another site**: a partner, a company directory, an OAuth provider. The browser goes
to the other site with a value only it knows (`state`), comes back with a code, the server trades the code for the
account, server to server, and signs the person in. That needs the session, sends the browser away and signs someone in:
two web-only capabilities and two [`Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#action)
lines, no controller. Since 2.21.0 (`webOnly`, `Route::action`).
## With Claude

```text
"Add 'Sign in with Partner': the code comes back to /auth/partner"
```

**Check**

+ `/signin/partner` answers `302` to the other site, with a `state`.
+ `/auth/partner` with a wrong or missing `state` goes to `/login`.
## By hand

`application/services/Account/PartnerSignIn.php` (`PARTNER_URL`, `PARTNER_CLIENT_ID` and `PARTNER_CLIENT_SECRET` in `.env`):

```php
<?php

use Caligrafy\AuthRoutes;
use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Database;
use Caligrafy\Service;
use Caligrafy\Web;

// GET /signin/partner: off to the other site, with a value only this browser knows
#[Capability(name: 'partner_sign_in', description: 'Sends the visitor to sign in on the partner site.', public: true, webOnly: true)]
class PartnerSignIn extends Service
{
    public function handle(array $input, Context $context)
    {
        $state = bin2hex(random_bytes(16));
        session('partner_state', $state);
        return Web::redirect(getenv('PARTNER_URL') . '/authorize?' . http_build_query(array(
            'client_id' => getenv('PARTNER_CLIENT_ID'),
            'redirect_uri' => session('home') . 'auth/partner',
            'state' => $state,
        )));
    }
}

// GET /auth/partner?code=&state=: back from the other site
#[Capability(name: 'partner_callback', description: 'Finishes a sign-in on the partner site.', public: true, webOnly: true)]
class PartnerCallback extends Service
{
    public $rules = array('code' => '', 'state' => '');

    public function handle(array $input, Context $context)
    {
        $expected = (string) session('partner_state');
        clearFromSession('partner_state');
        if ($expected === '' || !hash_equals($expected, (string) ($input['state'] ?? ''))) {
            return Web::redirect('/login');      // a sign-in that did not start in this browser
        }
        // the code is traded for the account, server to server, with the secret
        $answer = httpRequest(getenv('PARTNER_URL') . '/token', 'POST',
            array('code' => $input['code'] ?? '', 'client_secret' => getenv('PARTNER_CLIENT_SECRET')),
            array('Content-Type: application/json', 'Accept: application/json'));
        $username = 'partner' . preg_replace('/[^0-9]/', '', (string) ($answer['id'] ?? ''));
        if ($username === 'partner') {
            return Web::redirect('/login');
        }
        $users = new User('users');
        if (!$users->findByUsername($username)) {
            Database::table('users')->insert(array('username' => $username, 'passcode' => User::hashPassword(bin2hex(random_bytes(32)))));
        }
        AuthRoutes::signIn($users->findByUsername($username));
        return Web::redirect('/books');
    }
}
```

```php
    Route::action('/signin/partner', 'partner_sign_in');
    Route::action('/auth/partner', 'partner_callback');
```

`/signin/partner` answers `302` to the other site with a `state`. Back at `/auth/partner`, a wrong or missing `state` goes
to `/login`; the right one signs the person in and goes to `/books`. To remember how, for what only some sign-ins may do,
pass it as the third argument: `AuthRoutes::signIn($user, null, 'partner')`, then read it with `AuthRoutes::signedInBy()`
([below](#signedinby)). `AuthRoutes::signIn()` gives a new session id and a new
CSRF token. A page that stays open and keeps calling JSON uses `session_regenerate_id(true); Auth::authorize($user);`, as the
[face login recipe](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition#face-login) does, so its token stays valid.
## <a name="signedinby"></a>How a session signed in

Since 2.21.3, `AuthRoutes::signedInBy()` says how the current session signed in. `Route::auth` records `password` or
`passkey`. When you sign someone in yourself, say how:

```php
AuthRoutes::signIn($user, null, 'face');        // a new session id, a new CSRF token, and how it signed in
AuthRoutes::rememberSignIn('face');             // a page that stays open and signs in with Auth::authorize()
```

Use it for anything that changes how the account signs in. A face without a liveness check does not prove a person (a good
photo can pass), so a session opened that way must not be able to replace the face or add a passkey:

```php
if (AuthRoutes::signedInBy() !== 'password') {
    return Web::json(['error' => 'Sign in with your password to change your face'], 403);
}
```

It answers `null` when nobody is signed in or the sign-in was not recorded: treat that as not allowed. Signing out forgets it.

| Function of `Caligrafy\AuthRoutes` | What it does |
|---|---|
| `signIn($user, null, $how = null)` | a new session id, a new CSRF token, `Auth::authorize($user)`, and records `$how` |
| `rememberSignIn($how)` | records `$how`, for a page that signs in with `Auth::authorize()` (`null` forgets it) |
| `signedInBy()` | `password` or `passkey` through `Route::auth`, what you recorded otherwise, `null` when nobody recorded it or nobody is signed in |
| `signOut()` | `Auth::unauthorize()`, forgets `$how`, a new session id and CSRF token |

`Route::form` with `signsIn` records `password` (2.21.7); give another with `'signsInWith' => 'face'`.
## Common mistakes

+ **A web-only capability answers "There is no capability" over REST, MCP or `call`** (G143): only `Route::action`
  reaches it. That is what keeps the session and the redirects out of the other channels.
+ **`$context` is still the visitor after `AuthRoutes::signIn()`** (G144): it was built from the request. To call a
  capability as the person just signed in, build a new one: `Context::fromRequest(request(), 'web')`.
+ **A sign-in that did not start in this browser**: always check `state` with `hash_equals()` and forget it at once.
+ **Secrets in the code**: `PARTNER_CLIENT_SECRET` lives in `.env`, and the code is traded server to server.
## Related pages

+ [Sign-in, users and tokens](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#betweensites)
+ [Declarative routes: `Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#action)
+ [API: Caligrafy\AuthRoutes](https://github.com/caligrafy/caligrafy-quill/wiki/API-AuthRoutes) · [Caligrafy\Web](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#web)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Passkeys -->

A **passkey** (WebAuthn) is a key pair kept by the person's device (Touch ID, Windows Hello, Android, a security key or
a password manager) and unlocked with its biometrics or PIN. The private key never leaves the device and a passkey works
only on the domain it was made for: it cannot be phished or replayed. `Caligrafy\Passkey` (on
[lbuchs/webauthn](https://github.com/lbuchs/WebAuthn)) checks them on the server, `PasskeyClient`
(`public/js/services/passkey.js`) runs them in the browser, and `Route::auth(['passkeys' => true])` declares the four
endpoints. In `Route::auth` since 2.19.0.
## With Claude

```text
"people can add a passkey once signed in, and sign in with it"
```

For face sign-in with liveness and passkeys, say *"face sign-in with liveness and passkeys"*: Claude follows the
plugin's face login recipe ([Face detection and face login](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition#face-login)).

**Check**

+ Signed in, adding a passkey answers `201` and a row appears in `passkeys`.
+ Signed out, the passkey signs you in, and `AuthRoutes::signedInBy()` answers `passkey`.
## By hand

Before you start: the authentication module (`Auth::authentication('User', 'users');` in `web.php`).

1. **The table.** Add it with a [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations)
   (`php caligrafer.php migrate make add_passkeys`), with the statement of the face login recipe:
    ```sql
    CREATE TABLE IF NOT EXISTS passkeys (
      id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
      user_id INT NOT NULL,
      credential_id VARCHAR(255) NOT NULL,           -- base64url
      public_key TEXT NOT NULL,                      -- PEM
      sign_count INT UNSIGNED NOT NULL DEFAULT 0,
      name VARCHAR(64) NOT NULL DEFAULT 'Passkey',
      transports VARCHAR(255) NULL,
      aaguid CHAR(32) NULL,
      created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      last_used_at DATETIME NULL,
      CONSTRAINT uq_passkeys_credential_id UNIQUE (credential_id),
      CONSTRAINT fk_passkeys_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    ```
   then `php caligrafer.php migrate`.
2. **The endpoints**, in `application/config/routing/web.php`:
    ```php
    Route::auth(['home' => '/', 'passkeys' => true]);
    ```
   It declares `POST /passkey/register/options`, `/passkey/register` (signed in), `/passkey/login/options` and
   `/passkey/login`.
3. **The browser.** Load `passkey.js` (`APP_SERVICE_ROOT` is the address of `public/js/services/`) and call the
   endpoints with the session's `X-CSRF-Token` header. In a client app page, `apiHeaders()` gives it:
    ```js
    // <script src="<?php echo APP_SERVICE_ROOT.'passkey.js'; ?>"></script>
    const config = { headers: apiHeaders() };   // the session and its X-CSRF-Token
    const options = (await axios.post(env.home + 'passkey/register/options', {}, config)).data;
    await axios.post(env.home + 'passkey/register', await PasskeyClient.create(options), config);

    const login = (await axios.post(env.home + 'passkey/login/options', {}, config)).data;
    await axios.post(env.home + 'passkey/login', await PasskeyClient.get(login), config);
    ```
   `PasskeyClient.supported()` says whether the browser has passkeys at all.
4. **In production**, set in `.env` (they are not in `.env.example`):
    ```bash
    PASSKEY_RP_ID=example.com
    PASSKEY_ORIGIN=https://www.example.com
    ```
   Without them the request host is used, which is fine on `http://localhost`. Passkeys need `https`, except on
   `localhost`.
## <a name="endpoints"></a>Reference: the endpoints of `Route::auth`

| Endpoint | Who | Answers |
|---|---|---|
| `POST /passkey/register/options` | signed in | `200` the options for `PasskeyClient.create()`; `401` *Sign in first* |
| `POST /passkey/register` | signed in | `201` `{"passkey": {"name": ...}}` (the optional `name` field, *Passkey* by default) |
| `POST /passkey/login/options` | anyone | `200` the options for `PasskeyClient.get()`: any passkey of the site, no username to type |
| `POST /passkey/login` | anyone | `200` `{"user": {"id", "username", "permissions"}}`, a new session id and CSRF token, signed in by `passkey`; `401` *Unknown account* |

Every one needs the `X-CSRF-Token` header (`403` without it). A passkey error answers its status (`400` a failed
registration, `409` *This passkey is already registered*, `401` a failed sign-in) with `{"error": ...}`. The `level`
option of `Route::auth` applies: someone below it is refused like an unknown account.
## <a name="class"></a>Reference: `Caligrafy\Passkey`

```text
Registration (signed in):  registrationOptions($id, $username) -> navigator.credentials.create() -> register($response, $id)
Sign-in:                   authenticationOptions([$id])        -> navigator.credentials.get()    -> authenticate($response) returns the user id
```

+ `new Passkey($rpName = APP_NAME, $rpId = PASSKEY_RP_ID or the request host, $origin = PASSKEY_ORIGIN or APP_PROTOCOL://host, $table = 'passkeys')`.
+ `registrationOptions($userId, $userName, $displayName = null)`: the user id is the WebAuthn user handle, never an
  email or a name. `register($response, $userId, $name = null)` stores the credential and returns it without its public
  key. `authenticationOptions($userId = null)`: `null` lets the browser offer any discoverable passkey of the site.
  `authenticate($response)` returns the id of the user who owns the passkey. `remove($userId, $credentialId)`,
  `credentials($userId)`.
+ The challenge of each ceremony is kept in the session, used once, and expires after `$timeout` (120 s).
  `$userVerification` and `$residentKey` are `required`.
+ To store the credentials elsewhere, extend `Passkey` and override `credentials()`, `findCredential()`,
  `saveCredential()` and `touchCredential()`.

Every method: [API: Caligrafy\Passkey](https://github.com/caligrafy/caligrafy-quill/wiki/API-Auth#passkey).
## Common mistakes

+ **`Route::auth(['passkeys' => true])` and the face login recipe's passkey routes both declared**: the recipe's
  `Route::action` lines replace it; declare one of them.
+ **No `PASSKEY_RP_ID`/`PASSKEY_ORIGIN` in production**: the request host is used; set both (G42).
+ **`http://` on a server**: passkeys need `https`, except on `localhost`.
+ **Calling the endpoints without `X-CSRF-Token`**: `403`.
## Related pages

+ [Sign-in, users and tokens](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#routeauth): `Route::auth`
+ [Face detection and face login](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition#passkeys)
+ [How to sign in through another site](https://github.com/caligrafy/caligrafy-quill/wiki/How-To-Sign-In-Through-Another-Site#signedinby): `AuthRoutes::signedInBy()`
+ [API: Caligrafy\Passkey](https://github.com/caligrafy/caligrafy-quill/wiki/API-Auth#passkey)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.2-Stripe-%26-Cryptocurrency-Payment -->

Caligrafy takes card payments with **Stripe** (stripe-php 23: Stripe Checkout, payment intents and the Payment
Element, Stripe Connect for marketplaces) and crypto payments with the **Coinbase Business Checkouts API**. The
recommended way is a Stripe Checkout started by a capability, and a webhook (`Route::webhook`, 2.19.0) that records the
payment when Stripe says it went through.

**Since 2.26.0** the Stripe SDK is not installed in every project: run `php caligrafer.php add payments` once (it adds `stripe/stripe-php` to `composer.json` and `composer.lock`; commit both). Without it, `Caligrafy\Payment` and `Route::webhook(..., ['verify' => 'stripe'])` say which command to run, and `php caligrafer.php doctor` fails. A project updated from an earlier version keeps the package.
> #### ![](https://github.com/caligrafy/caligrafy-quill/blob/master/public/images/resources/play.png) [Accepting online payments](https://youtu.be/OqHfnKtM5VY)
>
> In this video you will learn how to accept online payments with Caligrafy using Stripe.
## With Claude

```text
/caligrafy-quill:new-capability Readers pay 5 USD for a membership with Stripe Checkout; record each paid session from Stripe's webhook
```

Claude writes a capability that starts the checkout, a `Route::form` that sends the reader to Stripe, a capability
that records the payment and `Route::webhook('/stripe/events', '<capability>', ['verify' => 'stripe'])` in
`application/config/routing/web.php`, with the table of the payments. It never writes your keys: you put them in `.env`.

**Check**

+ `.env` has your test keys (`PAY_PUBLIC_KEY_TEST`, `PAY_PRIVATE_KEY_TEST`) and `STRIPE_WEBHOOK_SECRET`, and they are
  not in git.
+ The capability that records payments refuses every caller but the webhook, and records a session once even when
  Stripe sends the event twice.
+ A payment with the test card `4242 4242 4242 4242` shows up in the table.
## By hand

**Bookshelf** sells a 5 USD membership. The commands run in the Docker server of the
[Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart) (`http://localhost:8080`); without Docker, drop
`docker compose exec dev-box`. Before you start: the sign-in pages of
[Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication) (`Route::auth`), and a
[Stripe](https://stripe.com/) account.

**1. The keys.** In the [Stripe dashboard](https://dashboard.stripe.com/apikeys), copy the test keys into `.env`:

```text
PAY_PUBLIC_KEY_TEST=pk_test_...
PAY_PRIVATE_KEY_TEST=sk_test_...
PAY_PUBLIC_KEY_PRODUCTION=pk_live_...
PAY_PRIVATE_KEY_PRODUCTION=sk_live_...
```

`APP_ENV=local` uses the test keys; `APP_ENV=production` the live ones.

**2. The payments table.** Write `application/models/Payments/create_db.sql`:

```sql
CREATE TABLE IF NOT EXISTS payments (
    id int NOT NULL AUTO_INCREMENT,
    stripe_session varchar(255) NOT NULL,
    amount int NOT NULL DEFAULT 0,
    status varchar(20) NOT NULL,
    created_at datetime NOT NULL DEFAULT now(),
    PRIMARY KEY (id),
    UNIQUE KEY payments_stripe_session_unique (stripe_session)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
```

Run `docker compose exec dev-box php caligrafer.php sql application/models/Payments/create_db.sql`.

**3. The capability that starts the checkout.** Write `application/services/Payments/StartCheckout.php`:

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Payment;
use Caligrafy\Service;

#[Capability(
    name: 'start_checkout',
    description: 'Starts a Stripe checkout for a 5 USD membership and returns the address of the Stripe payment page.',
    scope: 'payments:write'
)]
class StartCheckout extends Service
{
    public $rules = array('site' => '');
    public $descriptions = array('site' => 'The address of this site, for the way back from Stripe. APP_URL wins over it');

    public function handle(array $input, Context $context)
    {
        $site = rtrim((string) (getenv('APP_URL') ?: ($input['site'] ?? '')), '/');
        $result = (new Payment())->createCheckout(
            500,                                    // the amount in cents: 5.00
            'usd',
            1,                                      // the quantity
            array('name' => 'Bookshelf membership'),
            $site . '/membership/done?session_id={CHECKOUT_SESSION_ID}',
            $site . '/membership'
        );
        if (!$result['action_success']) {
            throw new \RuntimeException('Stripe refused the checkout: ' . $result['error']);
        }
        return array('url' => $result['url']);
    }
}
```

The two addresses are where Stripe sends the reader back: after paying, and with its back link. `APP_URL` (the app's
address, set by Caligrafy Cloud) wins over `site`. A capability does not read the session: the route gives it `site` in
step 5.

**4. The capability that records the payment.** Write `application/services/Payments/RecordPayment.php`:

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Database;
use Caligrafy\Service;
use Caligrafy\ServiceError;

#[Capability(
    name: 'record_payment',
    description: 'Records a paid Stripe checkout session. Called by the Stripe webhook.',
    mcp: false
)]
class RecordPayment extends Service
{
    public $rules = array('event' => 'required');

    public function handle(array $input, Context $context)
    {
        if ($context->actorType() !== 'webhook') {
            throw ServiceError::forbidden('Payments are recorded by the Stripe webhook only');
        }
        $event = $input['event'];
        if (($event['type'] ?? '') !== 'checkout.session.completed') {
            return array('ignored' => true);
        }
        $session = $event['data']['object'];
        if (($session['payment_status'] ?? '') !== 'paid') {
            return array('ignored' => true);
        }
        if (Database::table('payments')->where('stripe_session', $session['id'])->exists()) {
            return array('duplicate' => true);
        }
        Database::table('payments')->insert(array(
            'stripe_session' => $session['id'],
            'amount' => (int) $session['amount_total'],
            'status' => 'paid',
        ));
        return array('recorded' => true);
    }
}
```

+ The `actorType()` check matters: without it any signed-in person could call `record_payment` through the REST API
  with an event they made up.
+ Stripe sends an event again until it gets a `2xx`: the `exists()` check records a session once.

**5. The routes.** In `application/config/routing/web.php`, below `Route::auth(...)`:

```php
    Route::page('/membership', 'Bookshelf/membership', ['signedIn' => true, 'comeBack' => true]);
    Route::form('/membership/checkout', 'start_checkout', [
        'inputs' => fn () => ['site' => session('home')],             // only the server sets it, whatever the form sends
        'success' => fn ($result) => $result['url'],                  // a full address: the payment page of Stripe
        'back' => '/membership',
    ]);
    Route::page('/membership/done', 'Bookshelf/membership-done', ['signedIn' => true]);
    Route::webhook('/stripe/events', 'record_payment', ['verify' => 'stripe']);
```

`success` is a function here because the address comes from Stripe: the form sends the reader to it.

**6. The pages.** Write `application/views/Bookshelf/membership.pug`:

```pug
extends ../default/master/site

block title
  | Membership

block content
  main
    h1 Membership
    p A year of Bookshelf for 5 USD.
    form(method='POST', action=$home . 'membership/checkout')
      =csrf()
      button.btn.btn-primary(type='submit') Pay with Stripe
```

and `application/views/Bookshelf/membership-done.pug`:

```pug
extends ../default/master/site

block title
  | Thank you

block content
  main
    h1 Thank you
    p Your payment is being confirmed. It appears in your account within a minute.
```

**7. The webhook secret.** Stripe signs each event with the secret of its endpoint, `whsec_...`:

+ **On your computer**, the [Stripe CLI](https://docs.stripe.com/stripe-cli) forwards the test events:
  `stripe listen --forward-to localhost:8080/stripe/events` prints a `whsec_...` secret.
+ **Online**, in the dashboard (Developers, Webhooks), add the endpoint `https://<your app>/stripe/events` with the
  event `checkout.session.completed`, and copy its signing secret.

Put it in `.env`:

```text
STRIPE_WEBHOOK_SECRET=whsec_...
```

**8. Try it.** Sign in, open `/membership`, press *Pay with Stripe*: Stripe's page opens. Pay with the test card
`4242 4242 4242 4242`, any future date, any CVC. Stripe brings you back to `/membership/done`, and its event adds a row
to `payments` (`status` `paid`, `amount` `500`).

To try the webhook with no Stripe at all, sign an event yourself. Write `tests/sign.php` (`tests/` is never served):

```php
<?php
// php tests/sign.php <secret> <file>: the Stripe-Signature header of the file's body
$time = time();
$body = file_get_contents($argv[2]);
echo 't=' . $time . ',v1=' . hash_hmac('sha256', $time . '.' . $body, $argv[1]);
```

and `tests/event.json`:

```json
{"id":"evt_test_1","type":"checkout.session.completed","data":{"object":{"id":"cs_test_a1","payment_status":"paid","amount_total":500}}}
```

then, with `STRIPE_WEBHOOK_SECRET=whsec_test_docs` in `.env`:

```bash
curl -X POST -H "Content-Type: application/json" \
  -H "Stripe-Signature: $(docker compose exec -T dev-box php tests/sign.php whsec_test_docs tests/event.json)" \
  --data-binary @tests/event.json http://localhost:8080/stripe/events
```

| You send | You get |
|---|---|
| the event, signed | `200 {"received":true}` and a row in `payments` |
| the same event again | `200 {"received":true}`, still one row |
| `Stripe-Signature: t=1,v1=bad`, or no header | `400 {"error":{"code":"invalid_signature","message":"The Stripe signature is not valid"}}` |
| any event with `STRIPE_WEBHOOK_SECRET` empty | `500 {"error":{"code":"error","message":"The webhook is not set up"}}` |
| `docker compose exec dev-box php caligrafer.php call record_payment '{"event":{"type":"x"}}'` | `{"error":{"code":"forbidden","message":"Payments are recorded by the Stripe webhook only"}}` |

`docker compose exec dev-box php caligrafer.php audit` shows each event as `webhook /stripe/events record_payment ok`.

**Check**

+ `payments` has one row per paid session, whatever the number of times Stripe sent it.
+ A bad signature gets `400`; no one but the webhook can record a payment.
+ `.env` (keys and `STRIPE_WEBHOOK_SECRET`) is not committed.
## <a name="going-live"></a>Going live

With `APP_ENV=production`, payments use the `PAY_*_PRODUCTION` (live) keys: real cards, real money. Try one real
payment of a small amount, then refund it from the Stripe dashboard.

Stripe keeps **one list of webhook endpoints per mode, each with its own secret**:

+ Create the endpoint again in **live mode** and give the server its live signing secret (`STRIPE_WEBHOOK_SECRET`; on
  Caligrafy Cloud, `php caligrafer.php cloud secret set <app> STRIPE_WEBHOOK_SECRET=whsec_...`, then deploy).
+ A **test-mode** endpoint left on the production address fails: the server checks the test events with the live secret
  and answers `400`. Stripe retries, emails you, and stops sending to the endpoint after about nine days. Disable it
  (Developers, Webhooks, in test mode), or point it at a test server.

`php caligrafer.php doctor --only stripe,coinbase` checks the keys without creating anything: it reads the Stripe
balance (and says test or live mode) and lists one Coinbase checkout.
## <a name="webhook"></a>Reference: `Route::webhook`

```php
Route::webhook('/stripe/events', 'record_payment', ['verify' => 'stripe']);
Route::webhook('/hooks/github', 'record_push', ['verify' => function ($rawBody, $headers) {
    return hash_equals('sha256=' . hash_hmac('sha256', $rawBody, getenv('GITHUB_SECRET')), $headers['x-hub-signature-256'] ?? '');
}]);
```

| Option | Default | What it does |
|---|---|---|
| `verify` | required | `'stripe'`, or a function `($rawBody, $headers): bool` (header names in lower case); anything else stops `web.php` with an error |
| `secret_env` | `'STRIPE_WEBHOOK_SECRET'` | the `.env` setting that holds the Stripe secret |
| `secret` | | the secret itself, instead of `secret_env` |
| `tolerance` | `300` | seconds a Stripe signature stays valid |

| The event | The answer |
|---|---|
| signature checked, capability done | `200 {"received": true}` |
| bad or missing signature, a body that is not JSON | `400` |
| the capability refuses (`ServiceError`) | its status and error |
| no secret set, no such capability, an error in the capability | `500` (the reason goes to the PHP error log) |

+ `POST` only. No session and no CSRF token: the signature is the only proof.
+ The capability gets `['event' => the decoded JSON body]` and runs as the system, with full access
  (`$context->actorType()` is `webhook`). Declare `public $rules = array('event' => 'required');`.
+ Before trusting an amount for something valuable, ask Stripe again: `(new Caligrafy\Payment())->retrieveCheckout($id)`.

## Reference: `Caligrafy\Payment`

```php
// a checkout on a page hosted by Stripe
public function createCheckout($amount = 1000, $currency = 'usd', $quantity = 1, $productData = array(), $successUrl = '', $cancelUrl = '', $customerEmail = null, $locale = null, $paymentType = null, $payment_intent_data = array(), $vendor = array())
public function retrieveCheckout($sessionId)        // its status: data->payment_status is 'paid' once paid

// a payment intent, for your own payment page (the Payment Element)
public function createPaymentIntent($amount, $currency, $metadata = array(), $receipt_email = null, $description = '', $transfer = array())
public function retrieveIntent($intentId)

// a charge from card data (only for Stripe accounts allowed to send raw card numbers)
public function createTransaction($amount, $currency, $card, $receipt_email = null, $metadata = null, $description = '', $transfer = array(), $save = false)

public function getPublicKey()                       // the publishable key of the current APP_ENV
```

| Argument | |
|---|---|
| `$amount` | in cents (`500` is 5.00) |
| `$currency` | `'usd'`, `'eur'`... |
| `$productData` | `array('name' => ..., 'description' => ..., 'tax_code' => ...)` |
| `$successUrl` | where Stripe sends the customer after paying; `{CHECKOUT_SESSION_ID}` is replaced by the session id |
| `$cancelUrl` | where Stripe's back link goes |
| `$customerEmail`, `$locale` | fill in the email; the language of the page |
| `$paymentType` | leave `null`: the payment methods come from your Stripe dashboard |
| `$transfer`, `$payment_intent_data`, `$vendor` | Stripe Connect: `array('transfer_data' => ['destination' => 'acct_...'])`, `array('payment_intent_data' => ['application_fee_amount' => 200])`, `array('stripe_account' => 'acct_...')` |
| `$receipt_email`, `$metadata`, `$description` | a receipt address, your own key/value pairs, a description |

+ Every method returns `array('action_success' => true, 'data' => <Stripe object>)`, or
  `array('action_success' => false, 'error' => '<message>')`. `createCheckout()` adds `'url'`, the Stripe page;
  `createTransaction()` returns `'data' => array('confirmation' => <charge id>)`.
+ **Tax codes.** New Stripe accounts have Managed Payments on and refuse a product without a tax code. A
  `createCheckout()` without `tax_code` creates a classic Checkout (`managed_payments` off). To use Managed Payments,
  give the product its code (`txcd_10103001` SaaS for business use, `txcd_10000000` electronically supplied services);
  `'managed_payments' => array('enabled' => true|false)` in `$payment_intent_data` decides either way.
+ An empty `PAY_PRIVATE_KEY_*` makes `new Payment()` throw (`api_key cannot be the empty string`).

**Stripe Connect** (vendors paid out by Stripe):

```php
public function createAccount($email = null, $country = null, $type = 'express', $capabilities = array(), $accountInformation = array())
public function createAccountLink($accountId, $refreshUrl, $returnUrl, $type = 'account_onboarding')
public function createLoginLink($accountId)
public function updateAccount($accountId, $updates)
public function retrieve($accountId)
```

**ACH (bank) payments** go through Stripe Checkout: turn ACH on in your Stripe payment methods, and `createCheckout()`
offers it.
## <a name="cryptocurrency"></a>Cryptocurrency (Coinbase Business)

Caligrafy accepts USDC on Base through the **Coinbase Business Checkouts API**: Caligrafy creates a checkout and the
customer pays on a page hosted by Coinbase. Coinbase Commerce shut down on March 31, 2026, with its `CRYPTO_PAY_KEY`
setting; Coinbase Business serves merchants in the countries it supports (the United States and Singapore at the time
of writing).

**1. The keys.** Open a [Coinbase Business](https://www.coinbase.com/business) account, then create a secret API key for
the Business API in the Coinbase Developer Platform (Ed25519). In `.env`:

```text
# organizations/<org_id>/apiKeys/<key_id>
COINBASE_API_KEY_NAME=organizations/...
# the Ed25519 secret in base64, or a legacy ECDSA PEM written on one line with \n
COINBASE_API_KEY_SECRET=...
```

Each request is signed with a JWT built from them (valid 2 minutes); the secret never leaves your server.

**2. The capability.** Write `application/services/Payments/StartCryptoCheckout.php`:

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\CryptoPayment;
use Caligrafy\Service;

#[Capability(
    name: 'start_crypto_checkout',
    description: 'Starts a Coinbase checkout for a 5 USD membership and returns the address of the payment page.',
    scope: 'payments:write'
)]
class StartCryptoCheckout extends Service
{
    public $rules = array('site' => '');
    public $descriptions = array('site' => 'The address of this site, for the way back from Coinbase. APP_URL wins over it');

    public function handle(array $input, Context $context)
    {
        $site = rtrim((string) (getenv('APP_URL') ?: ($input['site'] ?? '')), '/');
        $result = (new CryptoPayment())->createTransaction(5, 'USD',
            array('name' => 'Bookshelf membership', 'description' => 'A year of Bookshelf'),
            array('user' => (string) $context->userId()),
            $site . '/membership/done', $site . '/membership');
        if (!$result['action_success']) {
            throw new \RuntimeException('Coinbase refused the checkout: ' . $result['error']);
        }
        return array('url' => $result['url']);
    }
}
```

**3. The route and the button.**

```php
    Route::form('/membership/crypto', 'start_crypto_checkout', [
        'inputs' => fn () => ['site' => session('home')],
        'success' => fn ($result) => $result['url'],
        'back' => '/membership',
    ]);
```

```pug
    form(method='POST', action=$home . 'membership/crypto')
      =csrf()
      button.btn.btn-secondary(type='submit') Pay with USDC
```

Coinbase needs `https://` addresses for both return links: try it on a server with HTTPS. Each checkout can be paid
once and expires after 24 hours by default.

```php
public function createTransaction($amount, $currency, $charge = array(), $metadata = array(), $redirectUrl = '', $cancelUrl = '', $expiresAt = null)
// ['action_success' => true, 'url' => <hosted payment page>, 'data' => <checkout>]
public function getCharge($chargeId)            // a checkout by id
public function getChargeStatus($chargeId)      // ACTIVE, PROCESSING, COMPLETED, EXPIRED, FAILED, DEACTIVATED, REFUNDED, PARTIALLY_REFUNDED, or 'unknown'
public function getCharges($filters = array())  // filters: status, startTime, endTime, descriptionQuery, pageSize, pageToken
public function cancelTransaction($id)          // deactivates an active checkout
public function refundTransaction($id, $amount = null, $currency = 'USDC', $reason = '') // full refund when $amount is null
```

`new CryptoPayment($keyName, $keySecret)` uses another account. Every method but `getChargeStatus()` returns
`array('action_success' => ..., 'data' => ...)` or `array('action_success' => false, 'error' => ...)`.
## Other ways

**The Payment Element on your own page.** For a payment form on your own page (cards, wallets, 3D Secure), opening the
page creates a payment intent and hands its client secret to the page Caligrafy ships, `default/pages/payment.pug` (with
`public/js/services/stripe_client.js`, the Payment Element and `stripe.confirmPayment`). A `GET` that changes something is
not a `Route::page`: it is a web-only capability, `application/services/Payments/PayPage.php`:

```php
<?php

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Payment;
use Caligrafy\Service;
use Caligrafy\Web;

#[Capability(name: 'pay_page', description: 'The payment page of a 5 USD membership.', webOnly: true)]
class PayPage extends Service
{
    public function handle(array $input, Context $context)
    {
        $payment = new Payment();
        $result = $payment->createPaymentIntent(500, 'usd');
        $secret = $result['action_success'] ? $result['data']->client_secret : null;
        return Web::view('default/pages/payment', array('clientSecret' => $secret, 'publicKey' => $payment->getPublicKey()));
    }
}
```

with `Route::action('/pay', 'pay_page', ['comeBack' => true]);` (no `public: true`: a visitor signs in first and comes
back). Record the payment from the webhook (`payment_intent.succeeded`), as above.

**A controller around Checkout.** Projects made before 2.19.0 create the checkout in a controller and show
`default/pages/checkout.pug` with its `checkoutUrl`. They keep working; `StartCheckout` and `Route::form` replace them.

**A charge from card numbers** (`createTransaction()` with `'tok_visa'` in test mode, or raw card data): only for Stripe
accounts allowed to handle raw card data. Prefer Checkout.
## Common mistakes

+ **Every event answers 500.** `STRIPE_WEBHOOK_SECRET` is empty, or holds the API key instead of the endpoint's
  `whsec_...`.
+ **Every event answers 400 online.** A test-mode endpoint checked with the live secret, or the reverse (see
  [Going live](#going-live)).
+ **A payment recorded twice.** Stripe retries: check that the session is not recorded yet, as `RecordPayment` does.
+ **Anyone can record a payment.** A webhook capability is also a REST capability: refuse callers whose
  `$context->actorType()` is not `webhook`.
+ **`the product tax code is missing`.** A product with Managed Payments on and no tax code: give a `tax_code`, or leave
  it out to get a classic Checkout.
+ **The way back breaks on a test server.** Build the return addresses from `APP_URL` or from `session('home')` given by
  the route's `inputs`, never a fixed `https://` address.
+ **A payment created in `Route::page`.** Pages take read-only capabilities: use `Route::form`, or `Route::action` when
  opening the address must create it.
## Related pages

+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#webhook)
+ [Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication)
+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)

<br /><br />
>[Next Section: Learn about Metadata & Social Rich Cards](https://github.com/caligrafy/caligrafy-quill/wiki/9.3-Metadata-&-Social-Rich-Cards)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition -->

**FaceDetect** finds faces in a camera, a video or a picture, and recognizes whose face it is, in the browser. It is a
JavaScript class, `FaceDetector` (`public/js/services/detect.js`), built on
[@vladmandic/face-api](https://github.com/vladmandic/face-api) 1.7.15 (the maintained successor of face-api.js) and
its TensorFlow.js models, which ship with Caligrafy in `public/resources/models`. The pictures never leave the browser
unless your code sends them. `FaceDetector` also gives face prints and a liveness check, which the server-side class
`Caligrafy\FaceLogin` uses for [face sign-in](#face-login).

**Since 2.26.0** the face-api models and the recognition example pictures are not in the release: `php caligrafer.php facedetect <name>` downloads them when it creates the app (pinned versions, every file's SHA-256 checked; offline it stops without creating anything), and `php caligrafer.php add facedetect` adds them to an existing project. A project that already has them keeps them.

In the Bookshelf example, a page checks that the photo of a library card shows exactly one face.
> #### ![](https://github.com/caligrafy/caligrafy-quill/blob/master/public/images/resources/play.png) [Detecting and Recognizing human faces with Caligrafy](https://youtu.be/uUcr6JM00S4)
>
> The video shows how the FaceDetect library detects and recognizes faces.
## With Claude

```text
/caligrafy-quill:new-app facedetect faces
```

Claude checks the name, runs `docker compose exec dev-box php caligrafer.php facedetect faces`, and gives you the address of the app
(`/apps/faces`). Then describe what the app should do: *"a page that checks that a library card photo has exactly one
face"*, or *"face sign-in with liveness and passkeys"*, for which Claude follows the plugin's face login recipe.

**Check**
- The detector is created with `Vue.markRaw(new FaceDetector('detection'))` in a Vue app.
- The markup keeps `#detector`, the media with `id="detection"`, `#apps` and `#infobar`.
- A blocked or missing camera is told to the person (`{ autoStart: false }` and `startStream()` in a `try`).
- Face sign-in is never one face print: it uses the server challenge, `liveness()` and `FaceLogin::verify()`, and
  offers a passkey.
## By hand

Run the commands in the project folder of the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart).
Without Docker (Composer with MAMP, XAMPP or LAMP), run the same commands without `docker compose exec dev-box` and
open your own address.

### Step 1: Create the app

```bash
docker compose exec dev-box php caligrafer.php facedetect faces
```

Expected:

```text
 Project created in the public folder.
 Type cd public/faces to access it anytime
```

It copies `framework/plugins/facedetect` to `public/faces`: `index.php` (the markup), `scripts/main.js` (a Vue app),
`css/styles.css` and `recognition/Flash/1.png` to `6.png` (pictures for the recognition example). No route to add: the
generic route of `web.php` serves every client app:

```php
Route::get('/apps/{appName}', 'Caligrafy\\Controllers\\ClientController'); // you can specify any path as long as it ends with appName
```

`Route::page('/apps/{appName}', 'Client/app', ['query' => ['app' => 'index']]);` is the same line, declared.

### Step 2: Try it

Open `http://localhost:8080/apps/faces` and allow the camera (the camera needs `https` or `localhost`). The camera
fills the screen, with six buttons at the bottom: **Detect**, **Full Detection** (box, landmarks, gender, age,
expression), **Recognize** (finds Flash), **Puppeteer** (a line drawing of the face without the video),
**Custom continuous** and **Custom callback** (they print to the browser console). When the camera is blocked, the
top of the screen says *The camera is blocked: allow it in the address bar, then reload the page.*

### Step 3: A page of your own: the library card photo

A client app can have several pages: `?app=<file>` opens `public/faces/<file>.php`. Create
**`public/faces/cardphoto.php`**:

```html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Card photo</title>
        <link rel="stylesheet" href="<?php echo session('public').'css/tokens.css';?>">
        <link rel="stylesheet" href="<?php echo session('public').'css/layout.css';?>">
        <link rel="stylesheet" href="<?php echo session('public').'css/look.css';?>">
    </head>
    <body class="cq-site">
        <section class="cq-hero cq-hero--page">
            <h1 class="cq-display">Library card photo</h1>
        </section>
        <section class="cq-band cq-band--tight">
            <div class="cq-inner cq-inner--narrow">
                <form id="photo" method="POST">
                    <div class="cq-field">
                        <label for="file">Your photo</label>
                        <input id="file" class="form-control" type="file" name="file" accept="image/png,image/jpeg">
                    </div>
                </form>
                <p id="result" class="cq-lead" role="status">Loading the face models...</p>
                <img id="detection" alt="Your photo" width="320" hidden>
            </div>
        </section>

        <script src="<?php echo APP_SERVICE_ROOT.'app.js?v='.@filemtime(PUBLIC_PATH.'js/services/app.js'); ?>"></script>
        <script>loadEnvironment(`<?php echo $env; ?>`);</script>
        <script src="<?php echo APP_SERVICE_ROOT.'face-api.min.js'; ?>"></script>
        <script src="<?php echo APP_SERVICE_ROOT.'detect.js?v='.@filemtime(PUBLIC_PATH.'js/services/detect.js'); ?>"></script>
        <script>loadVue({ scripts: ['cardphoto'] });</script>
    </body>
</html>
```

`loadVue({ scripts: [...] })` adds `public/faces/scripts/<name>.js` to the page (with or without Vue). Create
**`public/faces/scripts/cardphoto.js`**:

```js
// Checks that a library card photo shows exactly one face, in the browser: the photo is not sent anywhere
const detector = new FaceDetector('detection');   // an <img>: no camera
const image = document.getElementById('detection');
const result = document.getElementById('result');

detector.ready.then(() => { result.textContent = 'Choose a photo of your face.'; });

document.getElementById('file').addEventListener('change', (event) => {
    const file = event.target.files[0];
    if (!file) return;
    result.textContent = 'Checking...';
    image.onload = async () => {
        image.hidden = false;
        try {
            const print = await detector.faceprint(image);
            result.textContent = 'Good photo: one face, ' + Math.round(print.detection.score * 100) + '% sure.';
        } catch (error) {
            // 'No face found' or 'More than one face found'
            result.textContent = error.message + ': choose another photo.';
        }
    };
    image.src = URL.createObjectURL(file);
});
```

Open `http://localhost:8080/apps/faces?app=cardphoto`. The text changes to *Choose a photo of your face.* when the
models are loaded. Choose a portrait: *Good photo: one face, 99% sure.* Choose a picture with no face: *No face found:
choose another photo.*

### Step 4: Recognize your own people

1. Create one folder per person in `public/faces/recognition/`, named after them, with PNG pictures named `1.png`,
   `2.png`... (the same number for every person): `public/faces/recognition/Ada/1.png` to `4.png`.
2. In `public/faces/scripts/main.js`, change the **Recognize** app:

```js
this.loadApp({
    name: 'Recognize',
    method: this.detector.recognize,
    models: {
        labels: ['Flash', 'Ada'],   // the folder names
        sampleSize: 4               // pictures per person
    },
    options: {
        welcome: 'Show your face',
        recognition: true
    },
    algorithm: faceapi.SsdMobilenetv1Options
});
```

Reload `/apps/faces` and click **Recognize**: a box with the name and the distance (`Ada (0.41)`) follows each known
face, `unknown` the others. A picture in which no face is found is skipped, so use clear, front-facing portraits.

**Check**
- `/apps/faces` shows the six buttons and the camera (or the blocked-camera message).
- `?app=cardphoto` answers *Good photo* for one face and *No face found* / *More than one face found* otherwise.
- The browser console has no errors once the models are loaded.
## Reference

### The app's files

| File | What it is |
|---|---|
| `public/<app>/index.php` | the markup (opened by `/apps/<app>`); `?app=<file>` opens `public/<app>/<file>.php` |
| `public/<app>/scripts/main.js` | the Vue app that creates the detector and loads the apps |
| `public/<app>/css/styles.css` | the app's styles, after `public/css/camera.css` and `look.css` |
| `public/<app>/recognition/<Name>/<n>.png` | the pictures of each person to recognize |
| `public/js/services/detect.js` | `FaceDetector` and `LivenessTracker` |
| `public/js/services/face-api.min.js` | @vladmandic/face-api 1.7.15 (TensorFlow.js 4 included) |
| `public/resources/models/` | the models (`*-weights_manifest.json` + `*.bin`): SSD MobileNet v1, Tiny Face Detector, 68 landmarks, age and gender, recognition, expressions |

## FaceDetect markup components

### The screen: the camera fills it

```html
<body class="cq-camera-body">
    <div id="app" class="cq-camera">
        <section id="detector" class="cq-camera-media">
            <video id="detection" width="640" height="480" class="show" autoplay="autoplay" muted playsinline></video>
        </section>
        <header class="cq-camera-top">
            <h1 class="cq-camera-title">Face Detect</h1>
            <section id="infobar" class="cq-camera-status"></section>
        </header>
        <section class="controls cq-camera-bottom">
            <div id="apps" class="cq-camera-actions"></div>
        </section>
    </div>
```

| Part | Role |
|---|---|
| `#detector` | the block the detector draws in: its canvas (`#detectfaces`) is added there |
| `#detection` | the media: a `<video>` without `src` (the camera), a `<video src="...">` or an `<img>`. Its `width` and `height` only size it on the page: the canvas takes the size of the picture itself (the camera's resolution, `detector.mediaSize()`, 2.19.2), so the drawings stay on the faces whatever shape the camera sends |
| `#apps` | where `loadApp()` adds one button per app |
| `#infobar` | where `display()` writes messages (the `welcome` text, camera errors) |

`public/css/camera.css` (2.11.0+) gives the full-screen camera: `cq-camera-mirror` on `.cq-camera-media` for a selfie
camera, `.cq-camera-oval` (`.is-scanning`, `.is-success`, `.is-failed`) to guide a face, `.cq-camera-sheet` over a
`.cq-camera-backdrop` for a form over the camera, `button.cq-camera-button.is-primary` for the main action. A
[design style](https://github.com/caligrafy/caligrafy-quill/wiki/Design-Styles) restyles it through the `--cq-camera-*` tokens.

### Scripts

```html
<script src="<?php echo scripts('vue'); ?>"></script>          <!-- with Vue only -->
<script src="<?php echo APP_SERVICE_ROOT.'app.js?v='.@filemtime(PUBLIC_PATH.'js/services/app.js'); ?>"></script>
<script src="<?php echo APP_SERVICE_ROOT.'face-api.min.js'; ?>"></script>
<script src="<?php echo APP_SERVICE_ROOT.'detect.js?v='.@filemtime(PUBLIC_PATH.'js/services/detect.js'); ?>"></script>
<script>loadEnvironment(`<?php echo $env; ?>`);</script>
<script>loadVue({ scripts: ['main'] });</script>
```

`loadEnvironment()` defines `env` (with `env.home`, `env.appName`, `env.app_resources`, from which the models load).

### `new FaceDetector(media, options = {})`

`media` is the id of the `<video>`, `<img>` or `<canvas>`. The models start loading at once; `detector.ready` is a
promise that resolves when they are loaded. With `options.autoStart` (default `true`) and a `<video>` without a
source, the camera starts once the models are loaded. In a Vue 3 app, wrap it in `Vue.markRaw()` before putting it in
`data`: otherwise Vue wraps the canvases, streams and models in reactive proxies, which slows or breaks the detections.

```js
var detector = Vue.markRaw(new FaceDetector('detection'));
```

### Controlling the camera

To tell the person when the camera is blocked or missing, create the detector with `{ autoStart: false }` and start
the camera yourself. `startStream()` rejects with the browser's error: `NotAllowedError` (blocked), `NotFoundError`
(no camera); the error is also in `detector.streamError`.

```js
var detector = Vue.markRaw(new FaceDetector('detection', { autoStart: false }));

// in a Vue method: the promise waits for as long as the person takes to answer the permission prompt
async startCamera() {
    try {
        await detector.startStream({ video: { facingMode: 'user' }, audio: false });  // getUserMedia constraints
    } catch (error) {
        this.message = error.name === 'NotAllowedError' ? 'Allow camera access, then retry' : 'No camera found';
    }
}

detector.stopStream(); // turns the camera off
```

The buttons of `loadApp()` appear at once and work as soon as the models are loaded.

### `loadApp(settings)`

Without settings it adds **Detect** (boxes around faces). Otherwise:

| Setting | What it does |
|---|---|
| `name` | the button's text |
| `method` | `detector.draw` (draws the options below), `detector.recognize` (names the faces), or your function, which gets the detector |
| `custom` | `false` (default): `method` runs at every detection, every 100 ms, with `detector.app.detections`. `true`: `method` runs once when the button is clicked, with the canvas ready and no detection started |
| `algorithm` | `faceapi.TinyFaceDetectorOptions` (default, faster) or `faceapi.SsdMobilenetv1Options` (more accurate) |
| `options.welcome` | the message shown in the infobar |
| `options.detection` | draws a box around each face |
| `options.landmarks` | draws the 68 landmarks |
| `options.puppeteer` | hides the video and draws only the landmarks |
| `options.gender`, `options.age` | writes the estimated gender and age |
| `options.expression` | writes the most likely expression (neutral, happy, sad, angry, fearful, disgusted, surprised) when above 90% |
| `options.recognition` | loads the `models` for `recognize` |
| `models.labels` | the people: the folder names in `recognition/` |
| `models.sampleSize` | pictures per person (required: 0 loads nothing) |
| `models.images` | picture URLs to use instead of the folders (one list, or one list per label) |

### Face prints

`faceprint(media = null, minConfidence = 0.6)` returns the face print of the only face in the media:
`{ descriptor: [128 numbers], detection }` (the detection has `score` and `box`). It rejects with `No face found` or
`More than one face found`. Two prints of the same person are usually closer than 0.5
(`faceapi.euclideanDistance(a, b)`), prints of different people further than 0.6.

```js
await detector.ready;
const print = await detector.faceprint();            // the detector's media
const other = await detector.faceprint(someImage);   // any <img>, <video> or <canvas>
faceapi.euclideanDistance(print.descriptor, other.descriptor) < 0.5;  // probably the same person
```

A single face print is not a sign-in: a photo held to the camera gives one, and a print sent once can be sent again.

### Liveness

`liveness(options)` asks the person to do challenges in front of the camera and captures face prints while they move.
It follows the head turn (yaw) and the `happy` expression frame by frame: a turn starts facing the camera, a smile
starts neutral, so a photo fails.

```js
const result = await detector.liveness({
    challenges: ['turn-left', 'smile'],   // in this order; left and right are the person's own
    timeout: 20000,                       // ms for the whole check
    prints: 4,                            // face prints to capture
    onProgress: (p) => console.log(`${p.index + 1}/${p.total}: ${p.challenge}`)
});
// { passed: true, reason: null, challenges: [{ name, passed, at }], prints: [{ descriptor, challenge, at }], frames, duration }
```

| Option | Default |
|---|---|
| `challenges` | `['turn-left', 'smile']` (also `turn-right`; there is no `blink`) |
| `timeout` | `20000` ms |
| `prints` | `4`; the check passes with at least 3 (or `prints` when lower), the minimum of `FaceLogin::verify()` |
| `printInterval` | `350` ms between prints |
| `onProgress` | called with `{ challenge, index, total, passed }` when a challenge starts or passes |
| `thresholds` | overrides of `FaceDetector.LIVENESS_THRESHOLDS` = `{ frontalYaw: 0.15, turnYaw: 0.3, neutral: 0.3, smile: 0.8 }` |

It does not reject when the check fails: `passed` is `false` and `reason` says why (`Challenge not completed: smile`,
`More than one face found`, `Not enough face prints`). It rejects only when the models or the media cannot be used.
With a server challenge, keep `timeout` within its `expires_in`.

### Other methods and properties

| Member | What it is |
|---|---|
| `detector.app.detections` | the faces of the last detection (resized to the canvas): `detection.box`, `landmarks`, `descriptor`, `age`, `gender`, `expressions` |
| `detector.app.recognitions` | the matches, once `recognize` runs |
| `detector.app.canvas`, `detector.app.options` | the drawing canvas and the app's options |
| `detector.media` | the media element (`width`, `height`) |
| `detector.options` | `{ autoStart: true }` by default |
| `detector.streamError` | the last camera error, or `null` |
| `loadRecognition({ labels, images, sampleSize })` | promise of the `LabeledFaceDescriptors` of each person |
| `recognize(detector)`, `draw(detector)` | the drawing methods used by `loadApp()` |
| `detect(callback, recognize = false, fetchRate = 100)` | calls `callback` with the detections (or recognitions) every `fetchRate` ms |
| `detectFaces(app, detector)` | returns the function that starts the detection loop of an app |
| `prepareCanva(options)` | a new canvas over the media (stops the running app), fitted on the page the way the media is (`object-fit`) |
| `mediaSize()` | the size of the picture the media holds: `{width, height}` of the camera's resolution (`videoWidth` x `videoHeight`), an image's natural size, else its attributes (2.19.2). The canvas and `detector.app.detections` use it |
| `fetchImage(canvas, media)` | a data URL of the whole media drawn at the canvas's size |
| `display(message, output)`, `clearDisplay()` | write in the infobar, clear it |
| `FaceDetector.headYaw(points)`, `FaceDetector.frameSummary(points, expressions, at)`, `LivenessTracker` | the pure logic of the liveness check |

The face-api functions are available as `faceapi.*`: `detectAllFaces(media, options)` and `detectSingleFace()` (then
`.withFaceLandmarks()`, `.withFaceDescriptors()`, `.withAgeAndGender()`, `.withFaceExpressions()`),
`FaceMatcher(labeledDescriptors, 0.6)`, `LabeledFaceDescriptors(label, descriptors)`, `euclideanDistance(a, b)`,
`draw.drawDetections(canvas, detections)`, `draw.DrawBox(box, {label, boxColor})`,
`draw.DrawFaceLandmarks(landmarks, settings)`, `draw.DrawTextField(lines, anchor)`, `matchDimensions()`,
`resizeResults()`, `createCanvasFromMedia()`, `fetchImage(url)`. See the [face-api documentation](https://github.com/vladmandic/face-api).
## Face login

Face sign-in uses the browser for the camera and the server for every decision. **`Route::auth` has no face option**:
face sign-in is a set of web-only capabilities served by `Route::action`, because they keep a nonce in the session and sign
people in, and this is the template to use. The challenges come from the server, so a recording
of an earlier sign-in does not do them in the right order:

1. `POST /facelogin/start`: `FaceLogin::challenge($username)` returns a single-use nonce and 2 of the 3 challenges in a
   random order, kept in the session for 60 seconds.
2. The browser runs `detector.liveness({ challenges })` and sends `{ nonce, liveness, prints }`.
3. `POST /facelogin/login`: `FaceLogin::verify()` uses up the nonce (once, even when the check fails), requires the
   liveness result for the requested challenges in that order, and 3 to 12 prints of the same face that are **not
   identical** (identical prints are a replayed print, not a live camera). `FaceLogin::match()` then finds the account;
   prints already used by an earlier sign-in are refused.

**Honest limits.** Liveness in the browser stops photos, replayed requests and replayed prints. It does not stop a
determined attacker: a deepfake video through a virtual camera, or a modified page that sends made-up prints, can pass.
Use face sign-in as a convenience and require a [passkey](#passkeys) for sensitive accounts.

The steps need sign-in ([`Auth::authentication('User', 'users')`](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication)
and its `users` table).

**1. The tables.** Create **`application/models/FaceLogin/create_db.sql`**:

```sql
-- Face login and passkeys for the users of the authentication module (users table). Safe to run more than once.
CREATE TABLE IF NOT EXISTS face_prints (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  descriptor TEXT NOT NULL,                      -- encryptDecrypt('encrypt', json) with APP_KEY, never plain
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT fk_face_prints_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- hashes of the prints of accepted logins: the same prints sent again with a new nonce are refused
CREATE TABLE IF NOT EXISTS face_login_used_prints (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  print_hash CHAR(64) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT uq_face_login_used_prints_hash UNIQUE (print_hash),
  CONSTRAINT fk_face_login_used_prints_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- failures live in their own table, not on users: a change to the users row signs its owner out
CREATE TABLE IF NOT EXISTS face_login_attempts (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  attempt_key VARCHAR(191) NOT NULL,             -- client IP + username ('*' for 1:N)
  failures INT NOT NULL DEFAULT 0,
  locked_until DATETIME NULL,
  modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  CONSTRAINT uq_face_login_attempts_key UNIQUE (attempt_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- passkeys (Caligrafy\Passkey)
CREATE TABLE IF NOT EXISTS passkeys (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  credential_id VARCHAR(255) NOT NULL,           -- base64url
  public_key TEXT NOT NULL,                      -- PEM
  sign_count INT UNSIGNED NOT NULL DEFAULT 0,
  name VARCHAR(64) NOT NULL DEFAULT 'Passkey',
  transports VARCHAR(255) NULL,
  aaguid CHAR(32) NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  last_used_at DATETIME NULL,
  CONSTRAINT uq_passkeys_credential_id UNIQUE (credential_id),
  CONSTRAINT fk_passkeys_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```

```bash
docker compose exec dev-box php caligrafer.php sql application/models/FaceLogin/create_db.sql
```

Expected: `application/models/FaceLogin/create_db.sql run on <your database>`.

**2. The routes**, in **`application/config/routing/web.php`** (the page is the generic `/apps/facelogin`):

```php
Route::action('/facelogin/password', 'facelogin_password', ['method' => 'POST']);   // password sign-in from the page (before enrolment)
Route::action('/facelogin/register', 'facelogin_register', ['method' => 'POST']);   // new account from the page
Route::action('/facelogin/start', 'facelogin_start', ['method' => 'POST']);
Route::action('/facelogin/enroll', 'facelogin_enroll', ['method' => 'POST']);
Route::action('/facelogin/login', 'facelogin_login', ['method' => 'POST']);
Route::action('/facelogin/me', 'facelogin_me');
Route::action('/facelogin/logout', 'facelogin_logout', ['method' => 'POST']);
Route::action('/passkey/register/options', 'facepasskey_register_options', ['method' => 'POST']);
Route::action('/passkey/register', 'facepasskey_register', ['method' => 'POST']);
Route::action('/passkey/login/options', 'facepasskey_login_options', ['method' => 'POST']);
Route::action('/passkey/login', 'facepasskey_login', ['method' => 'POST']);
```

These passkey routes replace `Route::auth(['passkeys' => true])`: do not declare both. Each line serves a
[web-only capability](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#webonly): nothing but these routes reaches them. The page sends the
`X-CSRF-Token` header (`apiHeaders()`), which `Route::action` requires of every JSON call.

**3. The capabilities.** **`application/services/FaceLogin/FaceLoginCapabilities.php`**:

```php
<?php

use Caligrafy\Auth;
use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Database;
use Caligrafy\FaceLogin;
use Caligrafy\FaceLoginException;
use Caligrafy\Passkey;
use Caligrafy\Service;
use Caligrafy\Web;

/**
 * Face login with a liveness check (FaceDetector.liveness() + Caligrafy\FaceLogin) for the users of the authentication
 * module. Enrolment: a password sign-in (or a new account) first, then a liveness check. Login: a liveness check (the
 * challenges chosen by facelogin_start), then the face is matched.
 * Web-only capabilities: they keep a nonce in the session and sign people in, so only Route::action reaches them.
 */
abstract class FaceLoginAction extends Service
{
    const MAX_FAILURES = 5;
    const LOCK_SECONDS = 60;
    // what face login does for accounts that have a passkey:
    //   'face'    face alone logs in (convenience)
    //   'step-up' face, then the passkey (2 factors) - recommended for sensitive accounts
    //   'passkey' face login refused: the account logs in with its passkey only
    const PASSKEY_POLICY = 'step-up';
    const PENDING = '__face_pending';      // face checked, passkey expected

    protected function fail($code, $message) { return Web::json(['error' => $message], $code); }

    // lockout after MAX_FAILURES (kept outside users): [locked?, function($code, $message) recording a failure]
    protected function guard($key) {
        $now = gmdate('Y-m-d H:i:s');
        $attempt = Database::toArray(Database::execute('SELECT * FROM face_login_attempts WHERE attempt_key = ?', [$key]))[0] ?? null;
        $locked = $attempt && $attempt['locked_until'] && $attempt['locked_until'] > $now;
        $failed = function ($code, $message) use ($attempt, $key, $now) {
            $failures = ($attempt && (!$attempt['locked_until'] || $attempt['locked_until'] <= $now) ? (int)$attempt['failures'] : 0) + 1;
            $lock = $failures >= self::MAX_FAILURES ? gmdate('Y-m-d H:i:s', time() + self::LOCK_SECONDS) : null;
            Database::execute('INSERT INTO face_login_attempts (attempt_key, failures, locked_until, modified_at) VALUES (?, ?, ?, ?)
                               ON DUPLICATE KEY UPDATE failures = VALUES(failures), locked_until = VALUES(locked_until), modified_at = VALUES(modified_at)',
                              [$key, $lock ? 0 : $failures, $lock, $now]);
            return $this->fail($code, $message);
        };
        return [$locked, $failed];
    }

    // a new session id on every sign-in (fixation). The page stays open, so its CSRF token stays: not AuthRoutes::signIn()
    protected function mayChangeSignIn() {   // a face alone does not prove a person: a photo can pass
        return in_array(\Caligrafy\AuthRoutes::signedInBy(), ['password', 'passkey', 'face+passkey'], true);
    }

    protected function signIn($user, $factors, $status = 200) {
        session_regenerate_id(true);
        Auth::authorize($user);
        \Caligrafy\AuthRoutes::rememberSignIn(implode('+', $factors));   // what mayChangeSignIn() reads
        return Web::json(['user' => ['username' => $user->username], 'factors' => $factors, 'enrolled' => count($this->enrolled((int)$user->id)) > 0], $status);
    }

    protected function username($input) {
        $username = trim((string)($input['username'] ?? ''));
        return $username === '' || preg_match('/^[A-Za-z0-9._@-]{1,100}$/', $username) ? $username : null;
    }

    protected function enrolled($userId = null) {    // [['user' => id, 'descriptor' => [128]], ...]
        $sql = 'SELECT user_id, descriptor FROM face_prints' . ($userId ? ' WHERE user_id = ?' : '');
        $rows = Database::toArray(Database::execute($sql, $userId ? [$userId] : [])) ?: [];
        return array_map(fn($r) => ['user' => (int)$r['user_id'], 'descriptor' => json_decode(encryptDecrypt('decrypt', $r['descriptor']), true)], $rows);
    }
}

// POST /facelogin/start { username?, enroll? } -> { nonce, challenges, expires_in }
#[Capability(name: 'facelogin_start', description: 'Starts a face scan: a single-use nonce and the liveness challenges.', public: true, webOnly: true)]
class FaceLoginStart extends FaceLoginAction
{
    public $rules = ['username' => '', 'enroll' => ''];

    public function handle(array $input, Context $context) {
        if (!empty($input['enroll'])) {                           // enrolment: the signed-in account
            return $this->mayChangeSignIn() ? Web::json(FaceLogin::challenge(user()->username)) : $this->fail(401, 'Log in with your password first');
        }
        $username = $this->username($input);
        if ($username === null) { return $this->fail(422, 'Invalid username'); }
        return Web::json(FaceLogin::challenge($username));
    }
}

// POST /facelogin/enroll { nonce, liveness, prints } - signed-in people only
#[Capability(name: 'facelogin_enroll', description: 'Enrols the face of the signed-in person, after a liveness check.', public: true, webOnly: true)]
class FaceLoginEnroll extends FaceLoginAction
{
    public $rules = ['nonce' => '', 'liveness' => '', 'prints' => ''];

    public function handle(array $input, Context $context) {
        if (!$this->mayChangeSignIn()) { return $this->fail(401, 'Log in with your password first'); }
        $user = user();
        try {
            $prints = FaceLogin::verify($input, $user->username);
        } catch (FaceLoginException $e) {
            return $this->fail($e->getCode(), $e->getMessage());
        }
        if (FaceLogin::enrolledElsewhere($prints, $this->enrolled(), $user->id) !== null) {
            return $this->fail(409, 'This face is already enrolled on another account');
        }
        Database::execute('DELETE FROM face_prints WHERE user_id = ?', [$user->id]);
        foreach (array_slice($prints, 0, 5) as $print) {
            Database::execute('INSERT INTO face_prints (user_id, descriptor) VALUES (?, ?)', [$user->id, encryptDecrypt('encrypt', json_encode($print))]);
        }
        return Web::json(['enrolled' => min(5, count($prints))], 201);
    }
}

// POST /facelogin/password { username, password } - password sign-in before enrolment
#[Capability(name: 'facelogin_password', description: 'Signs in with a username and a password, before enrolling a face.', public: true, webOnly: true)]
class FaceLoginPassword extends FaceLoginAction
{
    public $rules = ['username' => '', 'password' => ''];

    public function handle(array $input, Context $context) {
        $username = $this->username($input);
        if (!$username) { return $this->fail(422, 'Enter a valid username'); }
        $key = 'pw|' . ($_SERVER['REMOTE_ADDR'] ?? '') . '|' . strtolower($username);
        [$locked, $failed] = $this->guard($key);
        if ($locked) { return $this->fail(429, 'Too many failed attempts: wait a minute'); }
        $user = (new User('users'))->findByUsername($username);
        if (!$user) {
            // same work as a real check so that response times do not reveal which usernames exist
            password_verify((string)($input['password'] ?? ''), '$2y$10$B0NLUgDUK3CbImwrVfa/FuOtSOKrb7DZTGG3USPSF4Comn4cy5RtG');
        }
        if (!$user || !$user->verifyPassword((string)($input['password'] ?? ''))) {
            return $failed(401, 'Invalid username or password');
        }
        Database::execute('DELETE FROM face_login_attempts WHERE attempt_key = ?', [$key]);
        return $this->signIn($user, ['password']);
    }
}

// POST /facelogin/register { username, password } - creates the account and signs it in, ready to enrol
// (the rules of the authentication module's /register: letters and digits, passwords of 8 to 72 characters)
#[Capability(name: 'facelogin_register', description: 'Creates an account and signs it in, ready to enrol a face.', public: true, webOnly: true)]
class FaceLoginRegister extends FaceLoginAction
{
    public $rules = ['username' => '', 'password' => ''];

    public function handle(array $input, Context $context) {
        $username = trim((string)($input['username'] ?? ''));
        $password = (string)($input['password'] ?? '');
        if (!preg_match('/^[A-Za-z0-9]{1,100}$/', $username)) { return $this->fail(422, 'Usernames use letters and digits (up to 100)'); }
        if (strlen($password) < 8 || strlen($password) > 72) { return $this->fail(422, 'Passwords need 8 to 72 characters'); }
        $users = new User('users');
        if ($users->findByUsername($username)) { return $this->fail(409, 'This username is taken'); }
        Database::execute('INSERT INTO users (username, passcode) VALUES (?, ?)', [$username, User::hashPassword($password)]);
        return $this->signIn($users->findByUsername($username), ['password'], 201);
    }
}

// POST /facelogin/login { username?, nonce, liveness, prints }
#[Capability(name: 'facelogin_login', description: 'Signs in the account whose enrolled face matches the prints.', public: true, webOnly: true)]
class FaceLoginLogin extends FaceLoginAction
{
    public $rules = ['username' => '', 'nonce' => '', 'liveness' => '', 'prints' => ''];

    public function handle(array $input, Context $context) {
        $username = $this->username($input);
        if ($username === null) { return $this->fail(422, 'Invalid username'); }
        $key = ($_SERVER['REMOTE_ADDR'] ?? '') . '|' . ($username !== '' ? strtolower($username) : '*');
        [$locked, $failed] = $this->guard($key);
        if ($locked) { return $this->fail(429, 'Too many failed attempts: wait a minute'); }

        try {
            $prints = FaceLogin::verify($input, $username);       // nonce (single use), liveness, prints
        } catch (FaceLoginException $e) {
            return $failed($e->getCode(), $e->getMessage());
        }
        $users = new User('users');
        $target = $username !== '' ? $users->findByUsername($username) : null;
        $match = $username === '' || $target ? FaceLogin::match($prints, $this->enrolled($target ? (int)$target->id : null)) : null;
        if (!$match) {
            return $failed(401, 'Face not recognized');           // same message whether or not the username exists
        }
        $hashes = array_map([FaceLogin::class, 'printHash'], $prints);
        $seen = Database::toArray(Database::execute('SELECT COUNT(*) AS n FROM face_login_used_prints WHERE print_hash IN (' . implode(',', array_fill(0, count($hashes), '?')) . ')', $hashes));
        if ((int)($seen[0]['n'] ?? 0) > 0) {
            return $failed(401, 'These face prints were already used: replay refused');
        }
        foreach ($hashes as $h) {
            Database::execute('INSERT IGNORE INTO face_login_used_prints (user_id, print_hash) VALUES (?, ?)', [$match['user'], $h]);
        }
        Database::execute('DELETE FROM face_login_attempts WHERE attempt_key = ?', [$key]);

        $user = $users->find($match['user']);
        $passkey = new Passkey();
        if (self::PASSKEY_POLICY !== 'face' && $passkey->credentials($user->id)) {
            if (self::PASSKEY_POLICY === 'passkey') { return $this->fail(403, 'This account logs in with its passkey'); }
            $_SESSION[self::PENDING] = ['user' => (string)$user->id, 'expires' => time() + 120];
            return Web::json(['step' => 'passkey', 'options' => $passkey->authenticationOptions($user->id)]);
        }
        return $this->signIn($user, ['face']);
    }
}

// GET /facelogin/me
#[Capability(name: 'facelogin_me', description: 'Who is signed in, and whether their face is enrolled.', readOnly: true, public: true, webOnly: true)]
class FaceLoginMe extends FaceLoginAction
{
    public function handle(array $input, Context $context) {
        if (!authorized()) { return $this->fail(401, 'Not logged in'); }
        return Web::json(['user' => ['username' => user()->username ?? null], 'enrolled' => count($this->enrolled((int)user()->id)) > 0]);
    }
}

// POST /facelogin/logout
#[Capability(name: 'facelogin_logout', description: 'Signs out.', public: true, webOnly: true)]
class FaceLoginLogout extends FaceLoginAction
{
    public function handle(array $input, Context $context) {
        Auth::unauthorize();
        session_regenerate_id(true);
        return Web::json(['loggedOut' => true]);
    }
}
```

**`application/services/FaceLogin/PasskeyCapabilities.php`**:

```php
<?php

use Caligrafy\Auth;
use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Passkey;
use Caligrafy\PasskeyException;
use Caligrafy\Web;

/**
 * Passkeys (Caligrafy\Passkey): registration for signed-in people, sign-in alone or after face login (step-up)
 */
abstract class FacePasskeyAction extends FaceLoginAction
{
    // the user whose face was just recognized, waiting for the passkey (FaceLoginAction::PENDING)
    protected function pending() {
        $p = $_SESSION[self::PENDING] ?? null;
        return is_array($p) && $p['expires'] >= time() ? $p['user'] : null;
    }
}

// POST /passkey/register/options
#[Capability(name: 'facepasskey_register_options', description: 'The options to register a passkey.', public: true, webOnly: true)]
class FacePasskeyRegisterOptions extends FacePasskeyAction
{
    public function handle(array $input, Context $context) {
        if (!in_array(\Caligrafy\AuthRoutes::signedInBy(), ['password', 'passkey', 'face+passkey'], true)) { return $this->fail(401, 'Log in with your password first'); }
        $user = user();
        return Web::json((new Passkey())->registrationOptions($user->id, $user->username));
    }
}

// POST /passkey/register { id, clientDataJSON, attestationObject, transports, name? }
#[Capability(name: 'facepasskey_register', description: 'Registers a passkey for the signed-in person.', public: true, webOnly: true)]
class FacePasskeyRegister extends FacePasskeyAction
{
    public $rules = ['id' => '', 'clientDataJSON' => '', 'attestationObject' => '', 'transports' => '', 'name' => ''];

    public function handle(array $input, Context $context) {
        if (!in_array(\Caligrafy\AuthRoutes::signedInBy(), ['password', 'passkey', 'face+passkey'], true)) { return $this->fail(401, 'Log in with your password first'); }
        try {
            $credential = (new Passkey())->register($input, user()->id, $input['name'] ?? null);
        } catch (PasskeyException $e) {
            return $this->fail($e->getCode(), $e->getMessage());
        }
        return Web::json(['passkey' => ['name' => $credential['name']]], 201);
    }
}

// POST /passkey/login/options: after face login only this user's passkeys, else any passkey of the site
#[Capability(name: 'facepasskey_login_options', description: 'The options to sign in with a passkey.', public: true, webOnly: true)]
class FacePasskeyLoginOptions extends FacePasskeyAction
{
    public function handle(array $input, Context $context) {
        return Web::json((new Passkey())->authenticationOptions($this->pending()));
    }
}

// POST /passkey/login { id, clientDataJSON, authenticatorData, signature, userHandle }
#[Capability(name: 'facepasskey_login', description: 'Signs in with a passkey, alone or after the face.', public: true, webOnly: true)]
class FacePasskeyLogin extends FacePasskeyAction
{
    public $rules = ['id' => '', 'clientDataJSON' => '', 'authenticatorData' => '', 'signature' => '', 'userHandle' => ''];

    public function handle(array $input, Context $context) {
        $pending = $this->pending();
        unset($_SESSION[self::PENDING]);
        try {
            $userId = (new Passkey())->authenticate($input);
        } catch (PasskeyException $e) {
            return $this->fail($e->getCode(), $e->getMessage());
        }
        if ($pending !== null && $pending !== $userId) { return $this->fail(401, 'This passkey belongs to another account'); }
        $user = (new User('users'))->find($userId);
        if (!$user) { return $this->fail(401, 'Unknown account'); }
        session_regenerate_id(true);
        Auth::authorize($user);
        \Caligrafy\AuthRoutes::rememberSignIn($pending !== null ? 'face+passkey' : 'passkey');
        return Web::json(['user' => ['username' => $user->username], 'factors' => $pending !== null ? ['face', 'passkey'] : ['passkey']]);
    }
}
```

**4. The client.** Create the app with `docker compose exec dev-box php caligrafer.php facedetect facelogin`, then replace its `index.php`,
`css/styles.css` and `scripts/main.js` with the ones of section 5 of the face login recipe,
[`claude-plugin/skills/caligrafy/reference/recipes-face-login.md`](https://github.com/caligrafy/caligrafy-quill/blob/master/claude-plugin/skills/caligrafy/reference/recipes-face-login.md#5-client-facedetect-app).
It has a **Sign in** tab (an oval guide with hints such as *Move a little closer*; the liveness check starts by itself
when the face is in the oval, with the prompts on the video) and an **Enrol your face** tab (sign in with a password or
create an account, scan the face, then try it or add a passkey). The browser calls the routes with
`{ headers: apiHeaders() }`.

**Check** (from the command line, before the camera)
- `POST /facelogin/start` with `{"username": "<a user>"}` answers `{"nonce": "<64 hex>", "challenges": [2 of turn-left, turn-right, smile], "expires_in": 60}`.
- `POST /facelogin/login` with a made-up nonce answers `401`, *Unknown or already used challenge: start again*.
- Four identical prints answer `422`, *Identical face prints: they must come from a live camera*; the prints of an
  accepted sign-in sent again with a new nonce answer `401`, *These face prints were already used: replay refused*.

### `Caligrafy\FaceLogin` (static)

| Member | What it does |
|---|---|
| `challenge($username = null, $count = null, $ttl = null)` | `['nonce' => 64 hex, 'challenges' => [...], 'expires_in' => 60]`, kept in the session (a new one replaces the old) |
| `verify($response, $username)` | uses up the nonce, checks the liveness result and the prints; returns the prints (`[[128 numbers], ...]`) or throws `FaceLoginException` (401 nonce, 422 liveness or prints) |
| `match($prints, $enrolled)` | `$enrolled` = `[['user' => id, 'descriptor' => [...]], ...]`; returns `['user', 'distance']` (mean below 0.5, none at 0.6 or more) or `null` |
| `checkPrints($prints)`, `enrolledElsewhere($prints, $enrolled, $user)`, `printHash($descriptor)`, `descriptor($d)`, `distance($a, $b)`, `consume($nonce, $username)` | helpers |
| `CHALLENGES` | `['turn-left', 'turn-right', 'smile']` |
| `$count` 2, `$ttl` 60, `$minPrints` 3, `$maxPrints` 12, `$distinct` 0.001, `$spread` 0.6, `$match` 0.5 | the settings |

### Passkeys

A passkey (WebAuthn) is a key pair kept by the person's device (Touch ID, Windows Hello, Android, a security key or a
password manager) and unlocked with its biometrics or PIN. The private key never leaves the device and a passkey works
only on the domain it was made for: it cannot be phished or replayed. `Caligrafy\Passkey` (on
[lbuchs/webauthn](https://github.com/lbuchs/WebAuthn)) checks them on the server, `PasskeyClient`
(`public/js/services/passkey.js`) runs them in the browser.

**Passkeys alone** (without face sign-in): create the `passkeys` table (the last statement of the SQL above) and add
`'passkeys' => true` to [`Route::auth`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#auth):

```php
Route::auth(['home' => '/', 'passkeys' => true]);
```

It declares `POST /passkey/register/options`, `/passkey/register` (signed in), `/passkey/login/options` and
`/passkey/login`. With face sign-in, the passkey capabilities above take these routes instead, because they
know whose face was just recognized.

```js
// <script src="<?php echo APP_SERVICE_ROOT.'passkey.js'; ?>"></script>
const config = { headers: apiHeaders() };   // the session and its X-CSRF-Token
const options = (await axios.post(env.home + 'passkey/register/options', {}, config)).data;
await axios.post(env.home + 'passkey/register', await PasskeyClient.create(options), config);

const login = (await axios.post(env.home + 'passkey/login/options', {}, config)).data;
await axios.post(env.home + 'passkey/login', await PasskeyClient.get(login), config);
```

+ `new Passkey($rpName = APP_NAME, $rpId = PASSKEY_RP_ID or the request host, $origin = PASSKEY_ORIGIN or APP_PROTOCOL://host, $table = 'passkeys')`;
  `registrationOptions($userId, $userName, $displayName = null)`, `register($response, $userId, $name = null)`,
  `authenticationOptions($userId = null)` (null: any passkey of the site), `authenticate($response)` (the user id),
  `remove($userId, $credentialId)`. To store them elsewhere, extend `Passkey` and override `credentials()`,
  `findCredential()`, `saveCredential()` and `touchCredential()`.
+ The challenge of each ceremony is kept in the session, used once, and expires after `$timeout` (120 s).
  `userVerification` and `residentKey` are `required`.
+ In production set `PASSKEY_RP_ID` (the domain, `example.com`) and `PASSKEY_ORIGIN` (`https://www.example.com`) in
  `.env` (they are not in `.env.example`). Passkeys need `https`, except on `localhost`.

| Setup | How | For |
|---|---|---|
| Face only | face sign-in with liveness (`FaceLoginAction::PASSKEY_POLICY = 'face'`) | low-risk apps, as a convenience |
| Face, then passkey | `'step-up'` (the default): accounts with a passkey confirm with it | most apps |
| Passkey only | `'passkey'`: face sign-in refused for accounts with a passkey | administrators, payments, health data |
| Passkey as fallback | the sign-in page always offers a passkey | every setup: the camera can be missing or blocked |

Enrol faces and passkeys only for people who are signed in with a password or a passkey, so that nobody can attach a face
or a passkey to someone else's account. `mayChangeSignIn()` checks it with
[`AuthRoutes::signedInBy()`](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#signedinby) (2.21.3): a session
opened with a face alone cannot replace the face or add a passkey, because a good photo can pass.

### Testing without a camera or a device

+ **A fake camera:** draw a picture on a canvas and give its stream to the page before the detector starts:
  `navigator.mediaDevices.getUserMedia = async () => canvas.captureStream(15);`. `faceprint()` works on it and
  `liveness()` must fail: this is the photo test.
+ **Virtual passkeys:** Chrome DevTools > More tools > WebAuthn > *Enable virtual authenticator environment*, then add
  an authenticator (internal, resident keys, user verification).
## Common mistakes

+ **A detector in Vue `data` without `Vue.markRaw()`.** The detections slow down or stop.
+ **Recognition pictures that differ in number**, or `sampleSize` missing: `sampleSize` 0 loads nothing.
+ **The camera on `http://` with another host than `localhost`.** Browsers allow the camera only on `https` or `localhost`.
+ **Calling a face route with no `X-CSRF-Token`**: `401` `[ERROR 1004]`, signed in or not. Send `apiHeaders()`.
+ **`AuthRoutes::signIn()` in a face capability**: it gives the session a new CSRF token, and the open page's next call is
  refused. The recipe uses `session_regenerate_id(true); Auth::authorize($user);`.
+ **Usernames that are email addresses** ([Signing in with an email](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#emailsignin)): `facelogin_register` checks its username itself: replace its letters-and-digits test with `filter_var($username, FILTER_VALIDATE_EMAIL)` and store it in lower case.
+ **A face print as a password.** Use the server challenge, `liveness()`, `FaceLogin::verify()`, and a passkey.
+ **`blink` in the challenges.** It was removed: `liveness()` refuses it.
+ **Both `Route::auth(['passkeys' => true])` and the passkey routes of the face login.** Keep one.
+ **An app folder with a reserved name**: `app`, `bot`, `__bots__`, `css`, `facedetect`, `fonts`, `images`, `js`, `ml`,
  `resources`, `uploads`.
## Related pages

+ [Machine learning](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.3-Machine-Learning): body poses and your own neural networks
+ [Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication) and [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#auth)
+ [Routes for client apps](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.2-Routes)
+ [Caligrafer: client apps](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#apps)
+ [@vladmandic/face-api](https://github.com/vladmandic/face-api)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.9.4-OpenAI%3A-ChatGPT%2C-GPTs%2C-DALL.E -->

Your application can ask OpenAI's models to write text (GPT) and to draw images (GPT image models; DALL.E was shut down
on May 12, 2026). The class `Caligrafy\OpenAI` sends the request; your key stays on the server. You put the call in a
**capability**, so the same feature reaches a web page, a Vue app, the REST API and AI agents (MCP) without a second
line of AI code. In the Bookshelf example, the capability `write_blurb` writes the back-cover blurb of a book, and
`draw_cover` draws a cover.

This page is about your application calling a model. The other direction, AI agents such as Claude using your
application, is [MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#mcp).

API calls cost money: create a key on [platform.openai.com/api-keys](https://platform.openai.com/api-keys) and add
credits to its project first.
## With Claude

Ask for the feature and name the capability:

```text
/caligrafy-quill:new-capability write_blurb ai:use read-only
Write a two-sentence back-cover blurb for a book from its title and author, with OpenAI. Show it on a /blurb page with a form.
```

Claude scaffolds `application/services/Bookshelf/WriteBlurb.php` with `docker compose exec dev-box php caligrafer.php service`, fills its `$rules` and
`handle()`, adds the routes to `application/config/routing/web.php` (`Route::page`, `Route::form`, and
`Route::capabilities`, `Route::mcp` when the project does not have them), writes the Pug view and a test in `tests/`.
For a chat app in Vue, `/caligrafy-quill:new-app app chat` follows the plugin's AI chat recipe.

**Check**
- `OPEN_AI_KEY` is in `.env`, never in a file of `public/` or in git; `docker compose exec dev-box php caligrafer.php doctor --only openai` says OK.
- The capability is not `public: true` (anyone could spend your credits) and has a scope (`ai:use`).
- `handle()` checks `$result['response']['error']` (OpenAI's own errors) and `api_success` (no answer at all).
- `docker compose exec dev-box php caligrafer.php test` passes without a real key: the test replaces the OpenAI client.
## By hand

The steps below add `write_blurb` (text) and `draw_cover` (image) to a project of the
[Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart) that has sign-in
([`Route::auth`](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#routeauth)), `Route::capabilities('/capabilities')`
and `Route::mcp('/mcp')` in `web.php`. Run the commands in the project folder. Without Docker (Composer with MAMP, XAMPP or LAMP), run the same commands without `docker compose exec dev-box` and open your own address.

### Step 1: Add the key

Open `.env` and set the key (keep the other lines as they are):

```text
OPEN_AI_KEY=sk-proj-...
OPEN_AI_MODEL=
OPEN_AI_IMAGE_MODEL=
```

Empty models mean the defaults: `gpt-6-luna` for text, `gpt-image-2` for images. Run:

```bash
docker compose exec dev-box php caligrafer.php doctor --only openai
```

It checks, without spending anything, that the key is accepted and that the default models are allowed for its
project. Without a key it prints `SKIP  OpenAI: OPEN_AI_KEY is not set`.

### Step 2: Create the capability

```bash
docker compose exec dev-box php caligrafer.php service Bookshelf/WriteBlurb --scope ai:use --read-only
```

Expected: `Created application/services/Bookshelf/WriteBlurb.php: capability 'write_blurb' (scope ai:use)`. Replace the
content of **`application/services/Bookshelf/WriteBlurb.php`** with:

```php
<?php
/**
 * WriteBlurb: writes the back-cover blurb of a book with OpenAI
 */

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\OpenAI;
use Caligrafy\Service;
use Caligrafy\ServiceError;

#[Capability(
    name: 'write_blurb',
    description: 'Writes a two-sentence back-cover blurb for a book from its title and author. Returns {blurb}.',
    scope: 'ai:use',
    readOnly: true
)]
class WriteBlurb extends Service
{
    public $rules = array(
        'title' => 'required|max_len,255',
        'author' => 'max_len,255',
    );

    public $filters = array(
        'title' => 'trim',
        'author' => 'trim',
    );

    public $descriptions = array(
        'title' => 'The title of the book',
        'author' => 'The author of the book',
    );

    // the OpenAI client comes through the constructor: a test can replace it ($this->fake(OpenAI::class, ...))
    public function __construct(private OpenAI $openai)
    {
    }

    public function handle(array $input, Context $context)
    {
        $book = $input['title'] . (!empty($input['author']) ? ' by ' . $input['author'] : '');
        $result = $this->openai->delegate(
            $book,
            'Write a back-cover blurb of two sentences. No spoilers.',
            CONVERSE
        );

        $response = $result['response'] ?? null;
        if (empty($result['api_success']) || !is_array($response)) {
            throw ServiceError::conflict('OpenAI did not answer: try again in a moment');
        }
        if (isset($response['error'])) {
            throw ServiceError::conflict('OpenAI refused: ' . ($response['error']['message'] ?? 'unknown error'));
        }

        return array('blurb' => trim($response[0]['message']['content'] ?? ''));
    }
}
```

What it does:
+ `readOnly: true`: it changes none of your data (agents may call it without asking).
+ The constructor gets a new `OpenAI` object (type `TEXT`) from the [container](https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection).
+ `delegate($input, $outcome, $command)` sends `CONVERSE` as the system prompt and the title with the instructions as
  the user message, with the default model.
+ The answer is in `$response[0]['message']['content']`. When OpenAI refuses (wrong key, no credits, unknown model),
  `$response['error']['message']` says why; when nothing comes back (timeout, network), `api_success` is `false`.
  Both become a `conflict` refusal with that message: a page shows it in `flash('error')`, REST answers 409.

Run `docker compose exec dev-box php caligrafer.php capabilities`: the list now has
`write_blurb  ai:use  read  Writes a two-sentence back-cover blurb...`.

### Step 3: Call it from the command line

```bash
docker compose exec dev-box php caligrafer.php call write_blurb title=Kindred author="Octavia E. Butler"
```

Expected (the text varies):

```json
{
    "data": {
        "blurb": "..."
    }
}
```

Without a title it answers `{"error": {"code": "invalid", ..., "fields": {"title": "The Title field is required"}}}`.

### Step 4: A page with a form

Add the routes to **`application/config/routing/web.php`**, before `Route::run();`:

```php
Route::page('/blurb', 'Bookshelf/blurb', ['signedIn' => true]);
Route::form('/blurb', 'write_blurb', ['success' => '/blurb', 'back' => '/blurb', 'flash' => '{blurb}']);
```

`Route::form` calls `write_blurb` with the form's fields, as the signed-in person, then goes back to `/blurb` with the
blurb as the `success` message (`{blurb}` is filled from the result). Create **`application/views/Bookshelf/blurb.pug`**:

```pug
extends ../default/master/site

block content
  section.cq-hero.cq-hero--page
    h1.cq-display Write a blurb

  section.cq-band.cq-band--tight
    .cq-inner.cq-inner--narrow
      if flash('error')
        .cq-alert.cq-alert--error(role='alert')= flash('error')
      if flash('success')
        p.cq-lead(role='status')= flash('success')
      form(method='POST', action="{$home}blurb")
        =csrf()
        .cq-field
          label(for='title') Title
          input#title.form-control(type='text', name='title', value=old('title'))
          if errors('title')
            p.cq-field-error= errors('title')
        .cq-field
          label(for='author') Author
          input#author.form-control(type='text', name='author', value=old('author'))
          if errors('author')
            p.cq-field-error= errors('author')
        button.btn.btn-primary(type='submit') Write
```

Open `http://localhost:8080/blurb`. Signed out, you go to `/login`. Signed in, type a title and click **Write**: the
page comes back with the blurb above the form. With an empty title it comes back with *The Title field is required*
under the field and the author you typed still there.

### Step 5: REST and AI agents

Nothing to add: `Route::capabilities` and `Route::mcp` serve every capability. Create a token for a program or an agent:

```bash
docker compose exec dev-box php caligrafer.php token create "blurb agent" --scopes ai:use --user 1
```

It prints `cq_...` once: store it as a secret. Then:

```bash
curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" \
  -H "Authorization: Bearer cq_..." \
  -d '{"title": "Kindred", "author": "Octavia E. Butler"}' \
  http://localhost:8080/capabilities/write_blurb
```

Expected: `200` and `{"data":{"blurb":"..."}}`. Without the token: `401`. An agent connected to `/mcp` with this token
sees the tool `write_blurb` and calls it with the same inputs.

### Step 6: Test it without a key

```bash
docker compose exec dev-box php caligrafer.php test make WriteBlurb
```

Replace **`tests/WriteBlurbTest.php`** with:

```php
<?php

use Caligrafy\OpenAI;
use Caligrafy\Testing\TestCase;

/**
 * php caligrafer.php test WriteBlurb
 */
final class WriteBlurbTest extends TestCase
{
    public function testItWritesABlurb(): void
    {
        // a stand-in for OpenAI: no request leaves the computer
        $this->fake(OpenAI::class, new class extends OpenAI {
            public function delegate($input = '', $outcome = '', $command = CONVERSE, $context = array(), $parameters = array())
            {
                return array('api_success' => true, 'type' => 'text',
                    'response' => array(array('message' => array('role' => 'assistant', 'content' => "A blurb for $input."))));
            }
        });

        $answer = $this->call('write_blurb', array('title' => 'Kindred', 'author' => 'Octavia E. Butler'), $this->user(1));

        $this->assertSame('A blurb for Kindred by Octavia E. Butler.', $answer['blurb']);
    }

    public function testItNeedsATitle(): void
    {
        $this->assertCapabilityFails('invalid', 'write_blurb', array(), $this->user(1));
    }

    public function testGuestsCannotUseIt(): void
    {
        $this->assertCapabilityFails('unauthenticated', 'write_blurb', array('title' => 'Kindred'), 'guest');
    }
}
```

```bash
docker compose exec dev-box php caligrafer.php test WriteBlurb
```

Expected: `OK (3 tests, 3 assertions)`.

### Step 7: Images

```bash
docker compose exec dev-box php caligrafer.php service Bookshelf/DrawCover --scope ai:use --read-only
```

Replace **`application/services/Bookshelf/DrawCover.php`** with:

```php
<?php
/**
 * DrawCover: draws a book cover with an OpenAI image model
 */

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\OpenAI;
use Caligrafy\Service;
use Caligrafy\ServiceError;

#[Capability(
    name: 'draw_cover',
    description: 'Draws a book cover from a title and a short description. Returns {image}: a PNG as a data URL.',
    scope: 'ai:use',
    readOnly: true
)]
class DrawCover extends Service
{
    public $rules = array(
        'title' => 'required|max_len,255',
        'idea' => 'max_len,1000',
        'quality' => 'contains_list,low;medium;high',
    );

    public $filters = array(
        'title' => 'trim',
        'idea' => 'trim',
    );

    public $descriptions = array(
        'title' => 'The title of the book',
        'idea' => 'What the cover should show',
        'quality' => 'low (fastest), medium (default) or high',
    );

    public function handle(array $input, Context $context)
    {
        $prompt = 'A book cover for "' . $input['title'] . '". ' . ($input['idea'] ?? '') . ' No text on the cover.';
        $openai = new OpenAI(IMAGE);
        $result = $openai->delegate($prompt, '', ANALYZE, array(), array(
            'size' => '1024x1536',
            'quality' => $input['quality'] ?? 'medium',
        ));

        $response = $result['response'] ?? null;
        if (empty($result['api_success']) || !is_array($response)) {
            throw ServiceError::conflict('No image: OpenAI did not answer in time, try the low quality');
        }
        if (isset($response['error'])) {
            throw ServiceError::conflict('OpenAI refused: ' . ($response['error']['message'] ?? 'unknown error'));
        }

        return array('image' => 'data:image/png;base64,' . ($response[0]['b64_json'] ?? ''));
    }
}
```

GPT image models answer with a **base64 image**, never a URL: the capability returns it as a `data:` URL that an `img`
shows as it is. For an image, `delegate()` sends the input as the `prompt` and ignores the command. (The container
always builds a `TEXT` client, so this capability creates its `IMAGE` client itself.)

An image is too large for a flash message, so the page calls the capability from the browser with the generated
JavaScript client. Write the client (run it again after every capability change):

```bash
docker compose exec dev-box php caligrafer.php client
```

Expected: `public/js/capabilities.js written: ... capabilities`. Add the page to **`web.php`**:

```php
Route::page('/cover', 'Bookshelf/cover', ['signedIn' => true]);
```

**`application/views/Bookshelf/cover.pug`**:

```pug
extends ../default/master/site

block content
  section.cq-hero.cq-hero--page
    h1.cq-display Draw a cover

  section.cq-band.cq-band--tight
    .cq-inner.cq-inner--narrow
      p#error.cq-alert.cq-alert--error(role='alert', hidden)
      form#cover(method='POST')
        .cq-field
          label(for='title') Title
          input#title.form-control(type='text', name='title', required)
        .cq-field
          label(for='idea') What the cover shows
          input#idea.form-control(type='text', name='idea')
        button.btn.btn-primary(type='submit') Draw
      img#image(alt='The cover', width='512', hidden)

  script(type='module', src="{$home}public/js/cover.js")
```

**`public/js/cover.js`**:

```js
import { drawCover, CapabilityError } from './capabilities.js'

const form = document.getElementById('cover')
const image = document.getElementById('image')
const error = document.getElementById('error')
const button = form.querySelector('button')

form.addEventListener('submit', async (event) => {
  event.preventDefault()
  error.hidden = true
  button.disabled = true
  button.textContent = 'Drawing...'
  try {
    const answer = await drawCover({ title: form.elements.title.value, idea: form.elements.idea.value, quality: 'low' })
    image.src = answer.image
    image.hidden = false
  } catch (e) {
    error.textContent = e instanceof CapabilityError ? (Object.values(e.fields || {}).join(' ') || e.message) : 'Something went wrong.'
    error.hidden = false
  } finally {
    button.disabled = false
    button.textContent = 'Draw'
  }
})
```

Open `http://localhost:8080/cover`, type a title and click **Draw**: the button says *Drawing...* and the cover
appears under the form. The client sends the session cookie and its CSRF token: no key in the page.

**Check**
- `docker compose exec dev-box php caligrafer.php capabilities` lists `write_blurb` and `draw_cover` with the scope `ai:use`.
- `/blurb` and `/cover` send signed-out visitors to `/login`.
- `docker compose exec dev-box php caligrafer.php test WriteBlurb` passes with no key in `.env`.
- `curl` without a token on `/capabilities/write_blurb` answers `401`.
- `grep -r OPEN_AI_KEY public/` finds nothing.
## Reference

### `new OpenAI($mode = TEXT)`

| Mode | Endpoint | Default parameters |
|---|---|---|
| `TEXT` | `https://api.openai.com/v1/chat/completions` | `model` = `OPENAI_DEFAULT_MODEL` only |
| `IMAGE` | `https://api.openai.com/v1/images/generations` | `model` = `OPENAI_DEFAULT_IMAGE_MODEL`, `n` 1, `size` `1024x1024`, `quality` `medium`, `output_format` `png` |

Only the model is sent by default for text: current reasoning models reject `temperature`, `top_p` and `max_tokens`.
Add the parameters your model supports (`max_completion_tokens`, `reasoning_effort`, `response_format`...).

### `delegate($input = '', $outcome = '', $command = ANALYZE, $context = array(), $parameters = array())`

+ **TEXT**: sends `messages` = the `$context` messages, then `{role: system, content: $command}`, then
  `{role: user, content: "$input\n\n$outcome\n"}`. `$outcome` may be an array (sent as `| a | b |`).
  `$context` is the earlier conversation (`['role' => 'user'|'assistant'|'system', 'content' => '...']`).
+ **IMAGE**: sends `prompt` = `$input` with `$parameters`; `$outcome`, `$command` and `$context` are not used.
+ `$parameters` are merged over the defaults.

| Command | System prompt sent |
|---|---|
| `CONVERSE` | `You are a helpful assistant:` |
| `SUMMARIZE` | `Summarize the following:` |
| `ANALYZE` (default) | `Analyze the following:` |
| `CORRECT` | `Fix the following:` |
| `CLASSIFY` | `Classify the following:` (the categories in `$outcome`) |
| `COMPLETE` | `Complete the following:`; with `[insert]` in the input, the model writes only the text that replaces it |
| `PREDICT` | `Predict based on the following:` |
| `RECOMMEND` | `Recommend about the following:` |
| `CUSTOM` | empty: put your own system message first in `$context` |

### The answer

```php
array(
    'api_success' => true,     // false only when nothing came back (timeout, network): response is then a message
    'response' => array(...),  // TEXT: the choices, the text in [0]['message']['content']
                               // IMAGE: the data, the base64 PNG in [0]['b64_json']
                               // or OpenAI's error body: ['error' => ['message' => ..., 'code' => ...]]
    'type' => 'text'           // 'text' or 'image', when something came back
)
```

`api_success` is `true` for an error body too: always check `isset($result['response']['error'])`.

### Other methods

| Method | What it does |
|---|---|
| `converse($parameters = array(), $attachments = array(), $method = 'POST', $additionalHeaders = array())` | sends the parameters as they are to the endpoint of the mode (`delegate()` uses it); same answer shape |
| `OpenAI::command($name)` | `'summarize'` -> `SUMMARIZE`... (`OpenAI::COMMANDS`), anything else -> `null` |
| `OpenAI::type($name)` | `'text'` -> `TEXT`, `'image'` -> `IMAGE`, anything else -> `null` |

When a command or a type comes from a form, resolve it with `OpenAI::command()` / `OpenAI::type()`, never with
`constant()`: `constant()` would accept the name of any constant, `.env` secrets included.

An `OpenAI` object keeps the parameters of its earlier calls (`converse()` merges each call's parameters into it): use
a new object per request, as the container does for each capability call.

### Models

| Constant | Model |
|---|---|
| `GPT6_LUNA` | `gpt-6-luna`: fastest, cheapest; the default (`OPENAI_DEFAULT_MODEL`, or `OPEN_AI_MODEL`) |
| `GPT6_SOL` | `gpt-6.1-sol` |
| `GPT6_ASTRA` | `gpt-6-astra`: the flagship (`GPT4_LATEST` and `GPT4_LATEST_VISION` point to it) |
| `GPT_IMAGE` | `gpt-image-2`: the image default (`OPENAI_DEFAULT_IMAGE_MODEL`, or `OPEN_AI_IMAGE_MODEL`) |
| `GPT_IMAGE_BEST` | `gpt-image-2.5-sunburst` |
| `GPT_IMAGE_FAST` | `gpt-image-2.5-flare` |
| `GPT3`, `GPT4`, `GPT4_32` | shut down by OpenAI |
| `GPT4O`, `GPT4OMINI` | retire on January 14, 2027 |

Pass another model with `$parameters`: `array('model' => GPT6_ASTRA)`. Image options: `size` (`1024x1024`, `1536x1024`,
`1024x1536`, `auto`), `quality` (`low`, `medium`, `high`, `auto`), `output_format` (`png`, `jpeg`, `webp`), `background`, `n`.

### `.env`

| Setting | Default |
|---|---|
| `OPEN_AI_KEY` | none: required |
| `OPEN_AI_MODEL` | `gpt-6-luna` |
| `OPEN_AI_IMAGE_MODEL` | `gpt-image-2` |

The constants of `OpenAI.php` (`TEXT`, `CONVERSE`, `GPT6_LUNA`...) exist once the class is loaded: a file that uses one
before any `OpenAI` (for example in a property default) stops with *Undefined constant*.
## Other ways

**The example controller.** `web.php` ships two commented routes to a demo page that sends a form to `delegate()`:

```php
Route::get('/ai', 'Caligrafy\\Controllers\\AIController');
Route::post('/ai', 'Caligrafy\\Controllers\\AIController@query');
```

The controller is `application/controllers/core/AI/AIController.php`, its view `application/views/AI/openai.pug`. The
routes are open to anyone who reaches the site and every request is billed to you: use them to explore, then write a
capability as above, which has a scope, a sign-in check, validation and every channel.

**An answer that is not JSON.** For streaming or custom headers, serve a web-only capability with
[`Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#action), and keep the AI call in a plain capability that it calls with
`$this->capability('write_blurb', $input, $context)`. A controller that creates `new OpenAI()` reaches only its one route.
## Common mistakes

+ **Reading only `api_success`.** It is `true` when OpenAI answers with an error (rejected key, no credits, unknown
  model). Check `$result['response']['error']`. A `429 insufficient_quota` means the project has no credits.
+ **Sending `temperature` or `max_tokens`** to a reasoning model: OpenAI refuses the request. Use `max_completion_tokens`.
+ **Looking for an image URL.** GPT image models return base64 in `[0]['b64_json']`.
+ **Slow images.** The HTTP client gives up after 30 seconds (`httpRequest()`): a `high` quality image can take longer
  and comes back with `api_success` false. Use `low` or `medium`.
+ **A public capability.** `public: true` lets anyone spend your credits. Keep a scope and sign-in.
+ **The key in the browser.** Never put `OPEN_AI_KEY` in a page, `public/` or a Vue build: the browser calls the
  capability, the server calls OpenAI.
+ **`form.title` in a script.** It is the form's own `title` attribute: read inputs with `form.elements.title`.
+ **`constant($_POST['command'])`.** Use `OpenAI::command()`.
## Related pages

+ [OpenAI: Assistants](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.5-Open-AI:-Assistants): conversations that remember and answer from your files
+ [Open source agents (Llama, Mistral...)](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.6-Open-Source-Agents-(llama,-Mistral-etc.)): the same with open models
+ [Build once: services, capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP)
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes): `Route::form`, `Route::page`
+ [Dependency injection](https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection) and [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App)
+ [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs): AI work that should not keep the page waiting
+ [Caligrafer: doctor](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#doctor)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.9.5-Open-AI%3A-Assistants -->

An **assistant** holds a conversation: it remembers what was said, follows your instructions and can answer from your
own files. `Caligrafy\Assistant` runs on OpenAI's Responses and Conversations APIs (OpenAI shut down its Assistants API
on August 26, 2026; see [Migrating from version 1](#migrating)). You put it in a capability, so the same assistant
answers a web page, a Vue app, the REST API and AI agents. In the Bookshelf example, the capability `ask_librarian`
answers questions about the books, from a catalog file, and remembers the conversation.

Nothing is stored on OpenAI for the assistant itself: its model, instructions and tools live in your code and are sent
with every answer. OpenAI keeps the **conversation** (`conv_...`) and, when you give files, a **vector store** (`vs_...`)
that indexes them.
## With Claude

```text
/caligrafy-quill:new-capability ask_librarian ai:use read-only
A librarian assistant (Caligrafy\Assistant) that answers questions about the books from application/files/catalog.md and
continues a conversation when it gets the conversation id back. A /librarian page to chat with it.
```

Claude scaffolds the services in `application/services/`, a page (Pug view and a script that calls the generated
client), the routes in `web.php` and a test that replaces the assistant.

**Check**
- `OPEN_AI_KEY` is in `.env` only; `docker compose exec dev-box php caligrafer.php doctor --only openai` says OK.
- The conversation id goes back to the caller and comes in again as an input: the capability keeps nothing in the session.
- The capability that uploads files is not reachable by agents (`mcp: false`) and needs an administrator (`level: 1`).
- Answers are shown as text (`textContent`, `{{ }}`), never as HTML.
## By hand

The project is the one of the [OpenAI page](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.4-OpenAI:-ChatGPT,-GPTs,-DALL.E):
`OPEN_AI_KEY` in `.env`, sign-in, `Route::capabilities('/capabilities')` and `Route::mcp('/mcp')`. Without Docker (Composer with MAMP, XAMPP or LAMP), run the same commands without `docker compose exec dev-box` and open your own address.

### Step 1: Write the catalog

Create **`application/files/catalog.md`** (the `application` folder is never served to browsers):

```text
# Bookshelf catalog

- Kindred, Octavia E. Butler, 1979. Shelf B, 2 copies.
- The Dispossessed, Ursula K. Le Guin, 1974. Shelf A, 1 copy.
```

### Step 2: A capability that indexes it

```bash
docker compose exec dev-box php caligrafer.php service Bookshelf/IndexCatalog --scope ai:admin
```

Replace **`application/services/Bookshelf/IndexCatalog.php`** with:

```php
<?php
/**
 * IndexCatalog: uploads the catalog file to OpenAI so that the librarian answers from it
 */

use Caligrafy\Assistant;
use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;
use Caligrafy\ServiceError;

#[Capability(
    name: 'index_catalog',
    description: 'Uploads application/files/catalog.md to OpenAI and returns the id of its vector store, for LIBRARIAN_STORE in .env.',
    scope: 'ai:admin',
    level: 1,
    mcp: false
)]
class IndexCatalog extends Service
{
    public $rules = array();

    public function __construct(private Assistant $assistant)
    {
    }

    public function handle(array $input, Context $context)
    {
        $file = APP_PATH . 'files/catalog.md';
        if (!is_file($file)) {
            throw ServiceError::notFound('Write the catalog in application/files/catalog.md first');
        }

        $this->assistant->name = 'Bookshelf catalog';
        $uploaded = $this->assistant->uploadAssistantFiles(array($file));
        if (empty($uploaded) || $this->assistant->vector_store_id === '') {
            throw ServiceError::conflict('OpenAI did not take the file: check OPEN_AI_KEY (php caligrafer.php doctor --only openai)');
        }

        return array('vector_store_id' => $this->assistant->vector_store_id, 'file_ids' => $uploaded);
    }
}
```

`uploadAssistantFiles()` sends the file to OpenAI (`POST /v1/files`) and creates a vector store named after the
assistant with it. Run it once from the command line (it has full access there):

```bash
docker compose exec dev-box php caligrafer.php call index_catalog
```

Expected:

```json
{
    "data": {
        "vector_store_id": "vs_...",
        "file_ids": [
            "file-..."
        ]
    }
}
```

Copy the `vs_...` id into **`.env`**:

```text
LIBRARIAN_STORE=vs_...
```

Every `.env` line becomes a constant: the capability below reads `LIBRARIAN_STORE`. Run `index_catalog` again after you
change the catalog (it creates a new store: put its id in `.env`).

### Step 3: The librarian

```bash
docker compose exec dev-box php caligrafer.php service Bookshelf/AskLibrarian --scope ai:use --read-only
```

Replace **`application/services/Bookshelf/AskLibrarian.php`** with:

```php
<?php
/**
 * AskLibrarian: a conversation with an OpenAI assistant that knows the bookshelf
 */

use Caligrafy\Assistant;
use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;
use Caligrafy\ServiceError;

#[Capability(
    name: 'ask_librarian',
    description: 'Asks the bookshelf librarian a question. Send the conversation id it returns to continue the same conversation. Returns {conversation, answer}.',
    scope: 'ai:use',
    readOnly: true
)]
class AskLibrarian extends Service
{
    public $rules = array(
        'question' => 'required|max_len,4000',
        'conversation' => 'alpha_numeric_dash|max_len,100',
    );

    public $filters = array(
        'question' => 'trim',
        'conversation' => 'trim',
    );

    public $descriptions = array(
        'question' => 'The question for the librarian',
        'conversation' => 'The conversation id of an earlier answer, to continue that conversation',
    );

    // the assistant comes through the constructor: a test can replace it ($this->fake(Assistant::class, ...))
    public function __construct(private Assistant $assistant)
    {
    }

    public function handle(array $input, Context $context)
    {
        $assistant = $this->assistant;
        $assistant->instructions = 'You are the librarian of a small bookshelf. Answer in three sentences at most.';
        if (defined('LIBRARIAN_STORE') && LIBRARIAN_STORE !== '') {
            $assistant->vector_store_id = LIBRARIAN_STORE;   // answer from the catalog (index_catalog)
        }

        if (!empty($input['conversation'])) {
            $assistant->thread_id = $input['conversation'];  // continue that conversation
        } else {
            $assistant->start();                              // a new conversation on OpenAI
            if ($assistant->thread_id === '') {
                throw ServiceError::conflict('OpenAI did not start the conversation: check OPEN_AI_KEY (php caligrafer.php doctor --only openai)');
            }
        }

        $assistant->createMessage($input['question'])->run();
        if ($assistant->status !== 'completed') {
            throw ServiceError::conflict('OpenAI did not answer: ' . ($assistant->last_response['error']['message'] ?? $assistant->status));
        }

        return array('conversation' => $assistant->thread_id, 'answer' => $assistant->text());
    }
}
```

What it does:
+ The container gives a new `Assistant` with no settings (creating it calls nothing on OpenAI); `handle()` sets its
  instructions and, when `LIBRARIAN_STORE` is set, its vector store, which the default `file_search` tool searches.
+ The first question opens a conversation (`start()`, `POST /v1/conversations`). The caller sends its id back with the
  next question, so the capability keeps nothing between calls and works the same for a page, REST and an agent.
+ `run()` sends the question with the instructions, the tools and the conversation (`POST /v1/responses`) and returns
  when the answer is there; `text()` is its text.

```bash
docker compose exec dev-box php caligrafer.php call ask_librarian question="Where is Kindred?"
```

Expected (the answer varies):

```json
{
    "data": {
        "conversation": "conv_...",
        "answer": "Kindred is on shelf B; there are 2 copies."
    }
}
```

Continue the same conversation:

```bash
docker compose exec dev-box php caligrafer.php call ask_librarian question="Who wrote it?" conversation=conv_...
```

### Step 4: A page to chat

The conversation id lives in the page, so the page calls the capability with the generated client. Write it:

```bash
docker compose exec dev-box php caligrafer.php client
```

Add to **`application/config/routing/web.php`**, before `Route::run();`:

```php
Route::page('/librarian', 'Bookshelf/librarian', ['signedIn' => true]);
```

**`application/views/Bookshelf/librarian.pug`**:

```pug
extends ../default/master/site

block content
  section.cq-hero.cq-hero--page
    h1.cq-display Ask the librarian

  section.cq-band.cq-band--tight
    .cq-inner.cq-inner--narrow
      ul#answers.cq-rows
      p#error.cq-alert.cq-alert--error(role='alert', hidden)
      form#ask(method='POST')
        .cq-field
          label(for='question') Your question
          input#question.form-control(type='text', name='question', required)
        button.btn.btn-primary(type='submit') Ask

  script(type='module', src="{$home}public/js/librarian.js")
```

**`public/js/librarian.js`**:

```js
import { askLibrarian, CapabilityError } from './capabilities.js'

const form = document.getElementById('ask')
const answers = document.getElementById('answers')
const error = document.getElementById('error')
const button = form.querySelector('button')
let conversation = ''   // the conversation id of the first answer: the next questions continue it

function add (who, text) {
  const row = document.createElement('li')
  row.className = 'cq-row'
  row.textContent = who + ': ' + text   // text, never HTML: the answer comes from a model
  answers.append(row)
}

form.addEventListener('submit', async (event) => {
  event.preventDefault()
  const question = form.elements.question.value.trim()
  if (!question) return
  error.hidden = true
  button.disabled = true
  add('You', question)
  try {
    const input = conversation ? { question, conversation } : { question }
    const answer = await askLibrarian(input)
    conversation = answer.conversation
    add('Librarian', answer.answer)
    form.reset()
  } catch (e) {
    error.textContent = e instanceof CapabilityError ? (Object.values(e.fields || {}).join(' ') || e.message) : 'Something went wrong.'
    error.hidden = false
  } finally {
    button.disabled = false
  }
})
```

Open `http://localhost:8080/librarian`, sign in, ask *Where is Kindred?* then *How many copies?*: both questions and
answers appear in the list, and the second answer knows the first.

### Step 5: Test it without a key

```bash
docker compose exec dev-box php caligrafer.php test make AskLibrarian
```

Replace **`tests/AskLibrarianTest.php`** with:

```php
<?php

use Caligrafy\Assistant;
use Caligrafy\Testing\TestCase;

/**
 * php caligrafer.php test AskLibrarian
 */
final class AskLibrarianTest extends TestCase
{
    public function testItAnswersAndKeepsTheConversation(): void
    {
        // a stand-in for the OpenAI assistant: no request leaves the computer
        $this->fake(Assistant::class, new class extends Assistant {
            public function start() { $this->thread_id = 'conv_test'; return $this; }
            public function run($additional_instructions = '', $instructions = null, $tools = [], $model = '', $metadata = null)
            {
                $this->status = 'completed';
                $this->response_text = 'Kindred is on shelf B.';
                return $this;
            }
        });

        $answer = $this->call('ask_librarian', array('question' => 'Where is Kindred?'), $this->user(1));

        $this->assertSame(array('conversation' => 'conv_test', 'answer' => 'Kindred is on shelf B.'), $answer);
    }

    public function testItNeedsAQuestion(): void
    {
        $this->assertCapabilityFails('invalid', 'ask_librarian', array(), $this->user(1));
    }
}
```

```bash
docker compose exec dev-box php caligrafer.php test AskLibrarian
```

Expected: `OK (2 tests, 2 assertions)`.

**Check**
- `docker compose exec dev-box php caligrafer.php capabilities` lists `ask_librarian` (`ai:use`, read) and `index_catalog` (`ai:admin`, writes).
- An MCP `tools/list` does not show `index_catalog`.
- `docker compose exec dev-box php caligrafer.php call ask_librarian question=x conversation="conv/../x"` is refused: *The Conversation field may
  only contain letters, numbers, dashes and underscores*.
- The page shows the answers as plain text.
## Reference

### `new Assistant($parameters = array())`

Creating an assistant calls nothing on OpenAI, unless you give it files.

| Parameter | Default | What it is |
|---|---|---|
| `name` | none | the name (also the name of its vector store) |
| `description` | none | kept in the object only |
| `instructions` | none | the system prompt sent with every answer |
| `model` | `ASSISTANT_DEFAULT_MODEL` (`gpt-6-luna`, or `OPEN_AI_MODEL`) | `ASSISTANT_GPT6_LUNA`, `ASSISTANT_GPT6_SOL`, `ASSISTANT_GPT6_ASTRA` |
| `tools` | `array(['type' => 'file_search'])` | add `['type' => 'code_interpreter']` to let it run code on the files |
| `metadata` | none | up to 16 string pairs, sent with the conversation and every answer |
| `file_paths` | none | local files: uploaded and indexed in a new vector store at once |
| `file_ids` | none | files already on OpenAI: indexed in a new vector store at once |
| `vector_store_id` | `''` | an existing vector store: reuse its files without uploading them again |

`file_search` gets `vector_store_ids` = the assistant's store (it is left out when there is no store);
`code_interpreter` gets `container: {type: auto, file_ids}`; the old tool name `retrieval` becomes `file_search`.

### Methods

| Method | Chainable | What it does |
|---|---|---|
| `start()` | yes | creates a conversation (`POST /v1/conversations`): `thread_id` = `conv_...` |
| `createMessage($content, $file_ids = [], $metadata = null, $role = "user")` | yes | queues a message for the next `run()`; `$role`: user, assistant, system or developer; `$file_ids` go to the code interpreter; `$metadata` is not used |
| `run($additional_instructions = '', $instructions = null, $tools = [], $model = '', $metadata = null)` | yes | sends the queued messages (`POST /v1/responses`) and waits for the answer; the arguments override the settings for this answer only |
| `retrieveResponse($timeout = 120, $interval = 2)` | yes | for version 1 code: polls only while the answer is `queued` or `in_progress` |
| `end()` | yes | deletes the conversation |
| `retrieve()` | yes | does nothing (version 1 code) |
| `text()` | no | the text of the last answer (`response_text`) |
| `listMessages()` | no | the items of the conversation stored on OpenAI |
| `uploadAssistantFiles($specified_paths = [])` | no | uploads files, adds them to the vector store (creates it when there is none), returns their ids |
| `deleteAssistantFile($file_id)` | no | removes a file from the store and deletes it on OpenAI; `true` when deleted |
| `delete()` | no | deletes the vector store: `true` when deleted (otherwise the assistant itself) |

### Properties

| Property | What it holds |
|---|---|
| `name`, `description`, `instructions`, `tools`, `metadata` | the settings (public: change them after creation) |
| `file_ids`, `file_paths`, `vector_store_id` | the files and their store |
| `thread_id` | the conversation id (`conv_...`): set it to continue a conversation |
| `run_id` | the last answer id (`resp_...`) |
| `status` | the last answer's status: `completed`, `failed`, `incomplete`... |
| `messages` | the messages of this object: `['id', 'role', 'content' => [['type' => 'input_text'|'output_text', 'text']]]` |
| `response_text` | the text of the last answer |
| `last_response` | the last raw answer from OpenAI, with `error.message` when it failed |
| `assistant_id` | not used (version 1) |
## <a name="migrating"></a>Migrating from version 1

| Version 1 (Assistants API) | Version 2 (Responses + Conversations) |
|---|---|
| `new Assistant([...])` created an assistant on OpenAI | nothing is created: the settings live in the object |
| `assistant_id` | not used: keep the name, instructions, model and tools in your code |
| thread (`thread_id`) | conversation (`thread_id` holds the `conv_...` id) |
| run (`run_id`) | response (`run_id` holds the `resp_...` id) |
| `run()` then `retrieveResponse()` | `run()` returns with the answer; `retrieveResponse()` only waits for background answers |
| `messages` held thread messages (`content[0]['text']['value']`) | `['role', 'content' => [['type', 'text']]]`; use `text()` for the last answer |
| files attached to the assistant | files indexed in a vector store (`vector_store_id`) |
| `retrieval` tool | `file_search` (`retrieval` is still accepted and converted) |

Threads of version 1 can no longer be read. To keep a history, send the stored messages with `createMessage()` before
the first `run()` of a new conversation.
## Other ways

**With the conversation in the session.** `$assistant->start()->createMessage('Hi')->run()->text()` works in a web-only
capability ([`Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#action)) or a controller you keep, with the conversation id kept in the session. It
serves that one route only, and a REST client or an agent has no session: keep the assistant in a capability and pass the
conversation id, as above.

**Plain chat without OpenAI's memory.** `OpenAI::delegate()` with the earlier messages in `$context` (see the
[OpenAI page](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.4-OpenAI:-ChatGPT,-GPTs,-DALL.E)) keeps the history
on your side, without conversations or files on OpenAI.
## Common mistakes

+ **Expecting the answer in `messages[...]['content'][0]['text']['value']`** (version 1). Use `text()`.
+ **Polling in a loop after `run()`.** `run()` already waits for the answer.
+ **Uploading the files on every question.** Upload once (`index_catalog`), keep the `vector_store_id`, pass it next time.
+ **`alpha_dash` for the conversation id.** In GUMP it refuses digits: use `alpha_numeric_dash`.
+ **Trusting a conversation id from anyone.** Anyone who has an id can continue that conversation: ids are long and
  random, but do not put secrets in a conversation that several people share.
+ **A missing key.** `start()` leaves `thread_id` empty and `run()` ends with `status` `failed`: check them, and run
  `docker compose exec dev-box php caligrafer.php doctor --only openai`.
## Related pages

+ [OpenAI: ChatGPT, GPTs, DALL.E](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.4-OpenAI:-ChatGPT,-GPTs,-DALL.E)
+ [Open source agents (Llama, Mistral...)](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.6-Open-Source-Agents-(llama,-Mistral-etc.))
+ [Build once: services, capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP)
+ [Dependency injection](https://github.com/caligrafy/caligrafy-quill/wiki/Dependency-Injection) and [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App)
+ [Caligrafer: call](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#call) and [client](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#client)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.9.1-Creating-Bots-with-Watson -->

A **bot** is a chat window where people talk to an assistant in plain language. Caligrafy connects to
[IBM watsonx Assistant](https://cloud.ibm.com/apidocs/assistant/assistant-v2): you design the conversation (intents,
answers, choices) in IBM's interface, and Caligrafy gives you the chat app (a small Vue 3 app in `public/<name>`) and
the server side (`Caligrafy\Watson`), which keeps your key on the server. In the Bookshelf example, the help desk
answers questions such as opening hours and loans: people use it in the chat window, and the capability `ask_helpdesk`
gives the same answers to pages, the REST API and AI agents.

You need an [IBM Cloud account](https://cloud.ibm.com/registration) with a watsonx Assistant on the **Plus plan or
higher** (the v2 API that Caligrafy uses needs it).
> #### ![](https://github.com/caligrafy/caligrafy-quill/blob/master/public/images/resources/play.png) [Creating Bots with Caligrafy](https://youtu.be/TVajzJIDwfA)
>
> The video shows how Caligrafy connects to IBM Watson to build your own bot.
## With Claude

```text
/caligrafy-quill:new-app bot helpdesk
```

Claude checks the name, runs `docker compose exec dev-box php caligrafer.php bot helpdesk`, and tells you the address to open
(`/bot/helpdesk?botSkillId=<assistant id>`) and the `.env` settings to fill. To reach the same assistant from pages,
REST and agents, ask for a capability too:

```text
/caligrafy-quill:new-capability ask_helpdesk ai:use read-only
Ask the watsonx help desk one question and return its text answer.
```

**Check**
- `WATSON_API_KEY`, `WATSON_URL` and `WATSON_ASSISTANT_ID` are in `.env`; `docker compose exec dev-box php caligrafer.php doctor --only watson` says OK.
- The chat page answers your first message; without `?botSkillId=` it says *No assistant here: add ?botSkillId=<assistant id> to the address of this page.*
- The bot's script calls the data routes with `apiHeaders()` (the session and its CSRF token), never an API key.
## By hand

Run the commands in the project folder of the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart).
Without Docker (Composer with MAMP, XAMPP or LAMP), run the same commands without `docker compose exec dev-box` and
open your own address.

### Step 1: Create the assistant on IBM Cloud

In watsonx Assistant, create an assistant and build its conversation (try it in IBM's preview first). Then collect:

+ the **API key** and the **instance URL** (IBM Cloud > your Assistant service > Service credentials):
  `https://api.<region>.assistant.watson.cloud.ibm.com/instances/<instance_id>`;
+ the **assistant id** and, for recent assistants, the **environment id** (Assistant settings, or Environments >
  API details).

### Step 2: Add the settings

Open `.env` and fill the Watson lines (add `WATSON_ASSISTANT_ID`, which is not in `.env.example`):

```text
WATSON_API_KEY=...
WATSON_URL=https://api.us-south.assistant.watson.cloud.ibm.com/instances/<instance_id>
WATSON_ENVIRONMENT_ID=
WATSON_API_VERSION=2024-08-25
WATSON_ASSISTANT_ID=<assistant id>
```

`WATSON_URL` has no `/v2` at the end: Caligrafy adds the path. Run:

```bash
docker compose exec dev-box php caligrafer.php doctor --only watson
```

Expected: `OK    Watson: key and assistant accepted ...` (with `WATSON_ASSISTANT_ID` it opens and closes a test session).

### Step 3: Create the chat app

```bash
docker compose exec dev-box php caligrafer.php bot helpdesk
```

Expected:

```text
 Project created in the public folder.
 Type cd public/helpdesk to access it anytime
```

It copies `framework/plugins/bot` to `public/helpdesk`: `index.php` (the chat markup) and `scripts/main.js` (the Vue
app); the style is `public/css/bot.css`. The template's `application/config/routing/web.php` already serves it, with one
page line and three data lines that name the example controllers. Since 2.21.0 they are two lines (replace them, or leave
them: they do the same):

```php
// BOT PAGE ROUTE: a botSkillId is given in the URL, for example ?botSkillId=62196ce3-0b22-4aea-b2f2-d39730c03797
Route::page('/bot/{appName}', 'Client/app', ['query' => ['app' => 'index', 'botSkillId']]);

// BOT DATA ROUTES: POST /__bots__/{appName}/communicate, POST /__bots__/{appName}/{appId}, DELETE /__bots__/{appName}
Route::bots();
```

Open `http://localhost:8080/bot/helpdesk?botSkillId=<assistant id>`. The chat says *Hi there!*; type a message and
press **Go**: the assistant's answer appears below it. Without `?botSkillId=`, or when the assistant cannot be reached
(wrong URL, key or plan), the chat says so under *Hi there!*.

### Step 4: The same assistant for pages, REST and agents

The chat app keeps a Watson session in the PHP session, which only a browser has. For one question at a time, from any
channel, write a capability:

```bash
docker compose exec dev-box php caligrafer.php service Bookshelf/AskHelpdesk --scope ai:use --read-only
```

Replace **`application/services/Bookshelf/AskHelpdesk.php`** with:

```php
<?php
/**
 * AskHelpdesk: one question to the watsonx Assistant of the bookshelf
 */

use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;
use Caligrafy\ServiceError;
use Caligrafy\Watson;

#[Capability(
    name: 'ask_helpdesk',
    description: 'Asks the bookshelf help desk (a watsonx Assistant) one question. Returns {answer, replies}: the text, and every reply as Watson sent it.',
    scope: 'ai:use',
    readOnly: true
)]
class AskHelpdesk extends Service
{
    public $rules = array(
        'question' => 'required|max_len,2000',
    );

    public $filters = array(
        'question' => 'trim',
    );

    public $descriptions = array(
        'question' => 'The question for the help desk',
    );

    public function handle(array $input, Context $context)
    {
        if (!defined('WATSON_ASSISTANT_ID') || WATSON_ASSISTANT_ID === '') {
            throw ServiceError::conflict('The help desk is not set up: add WATSON_ASSISTANT_ID to .env');
        }

        try {
            $watson = new Watson(WATSON_ASSISTANT_ID);   // opens a session (WATSON_URL, WATSON_API_KEY)
        } catch (Exception $e) {
            throw ServiceError::conflict('Watson could not be reached: ' . $e->getMessage());
        }

        $replies = $watson->communicate($input['question'])->getResponse() ?? array();
        $watson->closeSession();

        $texts = array();
        foreach ($replies as $reply) {
            if (($reply['response_type'] ?? '') === 'text') {
                $texts[] = $reply['text'];
            }
        }

        return array('answer' => implode("\n", $texts), 'replies' => $replies);
    }
}
```

Each call opens a session, sends the question and closes the session, so the assistant does not remember earlier
questions here. Run:

```bash
docker compose exec dev-box php caligrafer.php call ask_helpdesk question="When are you open?"
```

Expected (the text is your assistant's):

```json
{
    "data": {
        "answer": "We are open from 9 to 6, Monday to Saturday.",
        "replies": [
            {
                "response_type": "text",
                "text": "We are open from 9 to 6, Monday to Saturday."
            }
        ]
    }
}
```

With `Route::capabilities('/capabilities')` and `Route::mcp('/mcp')` in `web.php`, it is also
`POST /capabilities/ask_helpdesk` and the agent tool `ask_helpdesk`. A page shows it with a form, as on the
[OpenAI page](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.4-OpenAI:-ChatGPT,-GPTs,-DALL.E):
`Route::form('/helpdesk', 'ask_helpdesk', ['success' => '/helpdesk', 'back' => '/helpdesk', 'flash' => '{answer}'])`.

**Check**
- `docker compose exec dev-box php caligrafer.php doctor --only watson` is OK.
- The chat at `/bot/helpdesk?botSkillId=<assistant id>` answers.
- `docker compose exec dev-box php caligrafer.php call ask_helpdesk question=Hi` answers `data`; with `WATSON_ASSISTANT_ID` empty it answers
  `conflict`, *The help desk is not set up: add WATSON_ASSISTANT_ID to .env*.
## Reference

### `Caligrafy\Watson`

| Method | What it does |
|---|---|
| `new Watson($watson_assistant_id, $environment_id = null)` | opens a session; `$environment_id` defaults to `WATSON_ENVIRONMENT_ID`. Throws without `WATSON_URL` (*Set WATSON_URL to your watsonx Assistant instance URL...*) or when no session opens (*The session could not be initialized*) |
| `communicate($messageText, $skillVariables = null)` | sends a message; `$skillVariables` (an array) are the context variables of the main skill. Returns the object |
| `getResponse()` | the replies of the last message (the `output.generic` list) |
| `getLastExchange()` | the last turn: `['turn_count', 'user', 'response']` |
| `getConversation()` | every turn, by turn number |
| `getExchangeAt($turnCount)` | one turn, or `[]` |
| `getContext()`, `getSkillVariables()`, `getContextVariable($variable)` | the context Watson returned, its user-defined variables, one of them |
| `getSessionId()` | the session id |
| `closeSession()` | deletes the session on Watson |

`getResponse()` and `getLastExchange()` take the last turn **out** of the log: call one of them once per message.

Requests go to `{WATSON_URL}/v2/assistants/{assistant_id}[/environments/{environment_id}]/sessions...?version={WATSON_API_VERSION}`
with the key as `apikey` basic authentication.

### `.env`

| Setting | Default |
|---|---|
| `WATSON_API_KEY` | none: required |
| `WATSON_URL` | none: required, the instance URL without `/v2` |
| `WATSON_ENVIRONMENT_ID` | none: sessions are created on the assistant itself |
| `WATSON_API_VERSION` | `2024-08-25` |
| `WATSON_ASSISTANT_ID` | none: read by `doctor` and by your own code (the capability above) |

### Replies

| `response_type` | What the chat app does |
|---|---|
| `text` | shows `text`, then waits for typed input |
| `option` | shows `title` and one button per option (`label`; the value sent is `value.input.text`) |
| `image` | shows the image (`source`, `title`) |
| `pause` | when the context has an `action` and the page defines `window.executeBotAction(context)`, shows the `text` it returns and sends its `variables` with the next answer |

### The chat app

`public/<name>/scripts/main.js` keeps the conversation (`messages`) and what the bot waits for (`action`: a `text`
input or `button` options) and calls the data routes with axios and `{ headers: apiHeaders() }`:

| Route | Body | Answer |
|---|---|---|
| `POST __bots__/<name>/<assistant id>` | `{}` | `true` once the session is open (kept in the PHP session) |
| `POST __bots__/<name>/communicate` | `{text, variables?}` | `{action_success: true, response: [replies], context: {variables}}` |
| `DELETE __bots__/<name>` | | closes the session |

Messages are always shown as text, never as HTML. To change the look, edit `public/<name>/index.php` and keep the ids
and Vue bindings; the page route can be any path that ends with the app name, and `?app=<file>` opens another
`public/<name>/<file>.php` (letters, digits, `-` and `_`).
## Under the hood

`Route::bots()` declares the three data routes on the example controller `Caligrafy\Controllers\WatsonController`
(`application/controllers/core/AI/WatsonController.php`): `connect()` creates `new Watson($appId)` and keeps it,
serialized, in the session; `communicate()` sends the text and the variables and answers the replies and the context;
`end()` closes the session. The conversation lives in the PHP session, which only the browser has. Everything else (one
question from a page, REST or an agent) goes through a capability such as `ask_helpdesk`.
## Common mistakes

+ **`WATSON_URL` with `/v2` at the end**, or the URL of the IBM Cloud dashboard instead of the instance URL.
+ **A Lite plan.** The v2 API needs Plus or higher: sessions are refused.
+ **No `?botSkillId=` in the page address.** The chat cannot connect.
+ **An old bot client that sends the API key.** Since 2.7.0 the client sends `apiHeaders()`; a bot that sends the key
  gets `[ERROR 1004] Access Denied` once `LEGACY_API_KEY=false` (Caligrafy Cloud). Copy `framework/plugins/bot/scripts/main.js` again.
+ **A bot folder name that is reserved**: `app`, `bot`, `__bots__`, `css`, `facedetect`, `fonts`, `images`, `js`,
  `ml`, `resources`, `uploads`.
## Related pages

+ [OpenAI: Assistants](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.5-Open-AI:-Assistants): a conversation with an OpenAI model instead
+ [Build once: services, capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP)
+ [Routes for client apps](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.2-Routes)
+ [Caligrafer: client apps](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#apps) and [doctor](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#doctor)
+ [watsonx Assistant documentation](https://cloud.ibm.com/docs/watson-assistant)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.9.3-Machine-Learning -->

**ML Core** brings machine learning to the browser: it detects body poses in a camera, learns from pictures, and
trains small neural networks of your own. It is a JavaScript class, `MlCore` (`public/js/services/mlcore.js`), built
on [ml5.js](https://docs.ml5js.org) 1.4 (itself on TensorFlow.js), with [p5.js](https://p5js.org/reference/) 2.x for
drawing and controls. Everything runs in the browser: nothing is sent to your server unless your code sends it.

In the Bookshelf example, a page learns how many hours a book takes to read from its number of pages.
> #### ![](https://github.com/caligrafy/caligrafy-quill/blob/master/public/images/resources/play.png) [Creating and training an AI with Caligrafy](https://youtu.be/hBSWkaaBbNM)
>
> The video builds neural networks and computer vision with Caligrafy to detect people and objects and to predict outcomes.
## With Claude

```text
/caligrafy-quill:new-app ml reading
```

Claude checks the name, runs `docker compose exec dev-box php caligrafer.php ml reading` and gives you the addresses of the four example pages.
Then describe what to learn: *"a page that learns the reading time of a book from its number of pages"*.

**Check**
- The page loads ml5 (and p5 when it draws) before `mlcore.js`, as the scaffolded pages do.
- A page without a camera gives `media: 'none'`: a `<video id="video">` without a source starts the camera.
- Callbacks take `(results, error)`, in that order (ml5 1.x).
## By hand

Run the commands in the project folder of the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart).
Without Docker (Composer with MAMP, XAMPP or LAMP), run the same commands without `docker compose exec dev-box` and
open your own address.

### Step 1: Create the app

```bash
docker compose exec dev-box php caligrafer.php ml reading
```

Expected:

```text
 Project created in the public folder.
 Type cd public/reading to access it anytime
```

It copies `framework/plugins/ml` to `public/reading`: four pages (`index.php`, `posedetector.php`,
`featureextractor.php`, `neuralnetwork.php`), their scripts in `scripts/`, `css/styles.css` and an empty `resources/`
folder for models and data. The template's `web.php` already serves it at `/ml/<name>`. Declared, the line is:

```php
Route::page('/ml/{appName}', 'Client/app', ['query' => ['app' => 'index']]);
```

### Step 2: Try the examples

Allow the camera when the browser asks (it needs `https` or `localhost`):

| Address | Example | Pattern |
|---|---|---|
| `http://localhost:8080/ml/reading` | body pose: the keypoints and skeleton drawn on the camera, a red dot on the nose | detect and draw |
| `http://localhost:8080/ml/reading?app=posedetector` | learns poses you label with the buttons, then names them | learning with a person |
| `http://localhost:8080/ml/reading?app=featureextractor` | learns pictures you label from the camera (MobileNet) | learning with a person |
| `http://localhost:8080/ml/reading?app=neuralnetwork` | a neural network trained from data in code | learning without a person |

### Step 3: Your own neural network

Create **`public/reading/readingtime.php`** (opened with `?app=readingtime`):

```html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Reading time</title>
        <link rel="stylesheet" href="<?php echo session('public').'css/tokens.css';?>">
        <link rel="stylesheet" href="<?php echo session('public').'css/layout.css';?>">
        <link rel="stylesheet" href="<?php echo session('public').'css/look.css';?>">
        <script src="https://unpkg.com/ml5@1.4.0/dist/ml5.min.js"></script>
    </head>
    <body class="cq-site">
        <section class="cq-hero cq-hero--page">
            <h1 class="cq-display">Reading time</h1>
        </section>
        <section class="cq-band cq-band--tight">
            <div class="cq-inner cq-inner--narrow">
                <p id="status" class="cq-note">Training...</p>
                <form id="guess" method="POST">
                    <div class="cq-field">
                        <label for="pages">Pages</label>
                        <input id="pages" class="form-control" type="number" name="pages" min="1" value="350" required>
                    </div>
                    <button class="btn btn-primary" type="submit" disabled>Guess</button>
                </form>
                <p id="answer" class="cq-lead"></p>
            </div>
        </section>

        <script src="<?php echo APP_SERVICE_ROOT.'app.js?v='.@filemtime(PUBLIC_PATH.'js/services/app.js'); ?>"></script>
        <script>loadEnvironment(`<?php echo $env; ?>`);</script>
        <script src="<?php echo APP_SERVICE_ROOT.'mlcore.js'; ?>"></script>
        <script>loadVue({ scripts: ['readingtime'] });</script>
    </body>
</html>
```

`loadVue({ scripts: [...] })` adds `public/reading/scripts/<name>.js` to the page. Create
**`public/reading/scripts/readingtime.js`**:

```js
// A neural network that learns the hours a book takes to read from its number of pages (regression)
const myMl = new MlCore({
    media: 'none',    // no camera: the page has no <video id="video">
    canvas: 'none',
    brain: { type: 'neuralnetwork', options: { inputs: ['pages'], outputs: ['hours'], task: 'regression' } }
});

const status = document.getElementById('status');
const form = document.getElementById('guess');
const answer = document.getElementById('answer');

myMl.ready.then(() => {
    // the examples: pages read -> hours it took
    [[120, 3], [200, 5], [300, 7.5], [400, 10], [500, 12.5], [640, 16]]
        .forEach(([pages, hours]) => myMl.brain.addData({ pages: pages }, { hours: hours }));
    myMl.brain.normalizeData();
    myMl.brain.train({ epochs: 60 }, () => {
        status.textContent = 'Trained on 6 books.';
        form.querySelector('button').disabled = false;
    });
});

form.addEventListener('submit', (event) => {
    event.preventDefault();
    const pages = Number(form.elements.pages.value);
    myMl.brain.predict({ pages: pages }, (results, error) => {
        answer.textContent = error ? 'No guess: ' + error : 'About ' + results[0].value.toFixed(1) + ' hours';
    });
});
```

Open `http://localhost:8080/ml/reading?app=readingtime`. *Training...* becomes *Trained on 6 books.* after a few
seconds and **Guess** turns on. Click it: *About 8.7 hours* (the number varies a little from one training to the next).
Training pauses while the browser tab is hidden.

To keep what a network learned, `myMl.brain.save('reading')` downloads its files (the model `.json`, its
`_meta.json` and its `.weights.bin`); put them in `public/reading/resources/` and load them with
`myMl.brain.load(<the address of the model .json>, callback)` instead of training. To keep data on
the server (the readers' own reading times, for example), send it to a capability with the
[JS client](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#client).

**Check**
- The four example addresses open (with the camera allowed, the pose page draws on you).
- `?app=readingtime` shows *Trained on 6 books.* and a guess.
- The browser console has no errors.
## Reference

### `new MlCore(settings)`

| Setting | Default | What it is |
|---|---|---|
| `media` | `'video'` | the id of the `<video>` or `<img>`; a `<video>` without `src` starts the camera |
| `canvas` | `'canvas'` | the id of the drawing canvas |
| `brain` | `{ type: 'neuralnetwork', options: { inputs: 34, outputs: 2, debug: true, task: 'classification' } }` | the brain (below) |
| `filter` | `false` | `true`: keeps only the person and removes the background (ml5 `bodySegmentation`) |
| `hideVideo` | `false` | hides the video under the drawing |
| `backend` | `'webgl'` | the TensorFlow.js backend of the neural networks |

| `brain.type` | What it is | `brain.options` |
|---|---|---|
| `neuralnetwork` | an ml5 neural network | `inputs`, `outputs` (numbers or names), `task` (`classification` or `regression`), `debug`... |
| `featureextractor` | MobileNet, retrained on your labeled pictures | `epochs`, `batchSize` (for training); `version`, `alpha`, `task` (for MobileNet) |

`myMl.ready` is a promise that resolves when the brain and the camera are ready; `myMl.brain` is the ml5 object.

### Body poses

```js
var myMl = new MlCore();
myMl.detect((myMl) => {
    myMl.drawKeypoints(myMl);   // the 17 points
    myMl.drawSkeleton(myMl);    // the lines between them
    // myMl.poses: the poses of this frame
});
myMl.stopDetection();
```

`detect(callback, ...args)` runs ml5 `bodyPose` (MoveNet) on the media and calls `callback(myMl, ...args)` at every
frame. Each pose of `myMl.poses` has both shapes, scaled to the canvas:

```js
let pose = myMl.poses[0];
pose.keypoints        // 17 keypoints {x, y, confidence, name}: nose, left_eye, right_eye, left_ear, right_ear,
                      // left_shoulder, right_shoulder, left_elbow, right_elbow, left_wrist, right_wrist,
                      // left_hip, right_hip, left_knee, right_knee, left_ankle, right_ankle
pose.nose             // {x, y, confidence}, the same for every name
pose.box              // the box around the person
pose.pose.keypoints   // the earlier shape: [{part: 'leftEye', position: {x, y}, score}, ...]
pose.pose.leftEye     // camelCase names
pose.skeleton         // [[keypointA, keypointB], ...] for the visible connections
```

### Methods

| Method | What it does |
|---|---|
| `drawKeypoints(myMl)`, `drawSkeleton(myMl)` | draw the pose |
| `drawFeature(myMl, ['nose', 'left_eye'])` | draw some keypoints (snake_case or camelCase names) |
| `addData(myMl, label)` | body poses: adds the 34 coordinates of the current pose with a label |
| `addImage(myMl, label)` | feature extractor: adds the current frame with a label |
| `train(myMl, options = {})` | trains (`{ epochs, batchSize }`), then classifies continuously |
| `classify(myMl)` | classifies the current pose or frame; the best label is in `myMl.brain.results`, e.g. `Happy (93)%` |
| `save(name, callback, myMl)`, `load(fileOrPath, callback, myMl)` | download the model, load a saved one |
| `toP5(myMl)` | hands the canvas to p5 (call it in `setup()`): `draw()` then runs at every frame |
| `startStream()` | starts the camera (called by the constructor for a `<video>` without a source) |

On a neural network you can call ml5 directly: `myMl.brain.addData(inputs, outputs)`, `normalizeData()`,
`train(options, callback)`, `classify(input, (results, error) => ...)` (classification: `results[0].label`,
`results[0].confidence`), `predict(input, (results, error) => ...)` (regression: `results[0].value`), `save()`, `load()`.

### Drawing with p5

```js
function setup() {
    myMl.toP5(myMl);            // p5 now draws on the canvas
}

function draw() {               // runs only after toP5()
    if (myMl.poses.length > 0) {
        let nose = myMl.poses[0].nose;
        fill(255, 0, 0);
        ellipse(nose.x, nose.y, 50);
    }
}
```

p5 2.x has no `preload()`: use `async function setup()` to wait for something. Its DOM functions (`createButton`,
`createElement`) are part of p5 itself.

### Scripts of a page

```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/2.3.4/p5.min.js"></script>   <!-- when the page draws -->
<script src="https://unpkg.com/ml5@1.4.0/dist/ml5.min.js"></script>
<script src="<?php echo APP_SERVICE_ROOT.'app.js?v='.@filemtime(PUBLIC_PATH.'js/services/app.js'); ?>"></script>
<script>loadEnvironment(`<?php echo $env; ?>`);</script>
<script src="<?php echo APP_SERVICE_ROOT.'mlcore.js'; ?>"></script>
<script>loadVue({ scripts: ['main'] });</script>
```

The camera pages fill the screen (`public/css/camera.css`, 2.11.0+): the video and the canvas share one size
(640 x 480), the title and messages float at the top (`.cq-camera-top`, `#infobar`), the buttons at the bottom
(`.cq-camera-bottom`, `#apps`). See [the FaceDetect screen](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition#facedetect-markup-components).
## Common mistakes

+ **ml5 0.x code.** ML Core 2.0 follows ml5 1.x: `poseNet` became `bodyPose`, callbacks are `(results, error)`, models
  load asynchronously (wait for `myMl.ready`).
+ **`preload()` with p5 2.x.** It no longer exists.
+ **A page without a camera that keeps `<video id="video">`.** It asks for the camera: remove it and give `media: 'none'`.
+ **Training in a hidden tab.** The browser pauses it until the tab is visible again.
+ **An app folder with a reserved name**: `app`, `bot`, `__bots__`, `css`, `facedetect`, `fonts`, `images`, `js`, `ml`,
  `resources`, `uploads`.
## Related pages

+ [Face detection and face recognition](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition)
+ [Routes for client apps](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.2-Routes)
+ [Caligrafer: client apps](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#apps)
+ [ml5.js reference](https://docs.ml5js.org) and [p5.js reference](https://p5js.org/reference/)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.3-Metadata-%26-Social-Rich-Cards -->

When someone shares an address of your app on Facebook, LinkedIn, X, Slack or iMessage, those apps show a **rich
card**: a title, a line of description and an image, read from the page's `og:` and `twitter:` meta tags. Every page
built on `default/master/site` prints the card of your app (2.16.2+); you set it once with `metadata()`, and a page can
have its own.
> #### ![](https://github.com/caligrafy/caligrafy-quill/blob/master/public/images/resources/play.png) [Creating Rich Cards with Caligrafy](https://youtu.be/qgzufCEcg_I)
>
> In this video, we show how we can create Rich Cards that give search engines, social media networks and collaboration tools the ability to have more information about your site, application or product from the URL alone.
## With Claude

```text
Give Bookshelf its social card: "Bookshelf: your books, lent and returned", and each book page its own title
```

Claude fills the `metadata(...)` call of `application/config/config.php` and, for a page of its own, sets `$metadata`
in that view.

**Check**

+ The page source of `/books` has `og:title`, `og:description` and `og:image`.
+ The image is 1200 by 630 and its address is a full `https://` address.
+ The card shows in [opengraph.xyz](https://www.opengraph.xyz/) once the app is online.
## By hand

**1. The card of the app.** In `application/config/config.php`, replace the commented `metadata(...)` example with:

```php
metadata(array(
    'site_name' => 'Bookshelf',
    'title' => 'Bookshelf: your books, lent and returned',
    'description' => 'Know who has your books and when they come back.',
    'image' => 'https://bookshelf.example.com/public/images/resources/social-card.png',
    'image_alt' => 'Bookshelf',
));
```

Put a 1200 by 630 image at `public/images/resources/social-card.png`.

**2. Look at it.** Open the source of any page of `default/master/site` (`/books`, `/login`...). The `head` has, among the
image size, its `alt` and the other `twitter:` lines:

```text
<meta name="description" content="Know who has your books and when they come back."/>
<meta property="og:type" content="website"/>
<meta property="og:site_name" content="Bookshelf"/>
<meta property="og:title" content="Bookshelf: your books, lent and returned"/>
<meta property="og:description" content="Know who has your books and when they come back."/>
<meta property="og:image" content="https://bookshelf.example.com/public/images/resources/social-card.png"/>
<meta name="twitter:card" content="summary_large_image"/>
```

With `APP_URL` set (Caligrafy Cloud sets it), `og:url` is that address plus the page's path.

**3. A card per book.** Each book page shows its own title and summary. It uses the Bookshelf page of one book
(`application/views/Bookshelf/book.pug`, [lesson 04](https://github.com/caligrafy/caligrafy-quill-course/wiki/04-Your-First-Capabilities)
of the course), whose route in `application/config/routing/web.php` gives it `$book` (`get_book`: the book with its
`author` nested) and `$authors` (`list_authors`):

```php
    Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book', 'authors' => 'list_authors'], 'notFound' => 'Bookshelf/notfound']);
```

In `application/views/Bookshelf/book.pug`, make the first block set `$metadata` (the layout's `head` reads it):

```pug
block title
    - $metadata = array('title' => $book['title'] . ' on Bookshelf', 'description' => $book['summary']) + (array) metadata()
    = $book['title'] . ' · Bookshelf'
```

Leave the rest of the view (its `block content`) as it is.

Open the source of `http://localhost:8080/books/3`: `<meta property="og:title" content="Kindred on Bookshelf"/>` and
`<meta name="description" content="A young woman is pulled back in time to a plantation in Maryland."/>`; the image and
the rest come from `metadata()`. `$metadata` set outside a block (below `extends`) is not seen by the layout.

**4. Share links.** To show *Share: Facebook X LinkedIn Pinterest* under a page, add `'site_url' =>
'https://bookshelf.example.com'` to the `metadata(...)` of step 1 (the address the links share), and replace the
page's footer:

```pug
block footer
  footer.cq-footer
    include ../default/modules/share
```

The links share `site_url`, the app's address, not the page's.

**5. Test the card online.** Platforms read the card from the internet: on your computer, use a tunnel such as
[ngrok](https://ngrok.com/), or try it once the app is online. Then paste the address in
[opengraph.xyz](https://www.opengraph.xyz/), the [Facebook debugger](https://developers.facebook.com/tools/debug/sharing/)
or the [LinkedIn post inspector](https://www.linkedin.com/post-inspector/). Platforms keep a card for days: after a
change, press **Scrape again** in Facebook's debugger. X has no validator any more: preview a post with the address.

**Check**

+ `og:title` and `og:image` are in the source of every page.
+ `/books/3` has its own title.
+ A debugger shows the image, the title and the domain.
## <a name="card"></a>Reference: the card

`metadata(array $pairs)` keeps the pairs for the request (in the session) and returns them all; `metadata()` returns
them. A `null` value is ignored. `default/modules/metadata.pug` prints the card from the view's `$metadata`, else from
`metadata()`, and prints nothing without a `title`.

| Key | Becomes | |
|---|---|---|
| `title` | `og:title`, `twitter:title` | Required |
| `description` | `description`, `og:description`, `twitter:description` | Under 125 characters; X and LinkedIn do not show it |
| `image` | `og:image`, `twitter:image` (a large card) | A full address, 1200x630 |
| `image_width`, `image_height` | `og:image:width`, `og:image:height` | `1200` and `630` by default |
| `image_alt` | `og:image:alt`, `twitter:image:alt` | What the image shows |
| `site_name` | `og:site_name` | |
| `site_url` | `og:url`: this address plus the page's path; the address the share links share | `APP_URL` by default |

X and LinkedIn show only the image, the title and the domain: say what the app does in the title.

**`$metadata` in a view also prints a product block.** When a view of `site.pug` has `$metadata`, the layout adds
`default/modules/metadata_body.pug` to the page: hidden schema.org `Product` data (name, description, image, a price from
`amount`, `0.00` by default, a rating from `ratingValue` and `reviewCount`). It is meant for a page that sells one
product; give those keys their real values on such a page.

| Module | |
|---|---|
| `default/modules/metadata.pug` | the card, in the `head` of `site.pug` |
| `default/modules/metadata_body.pug` | the schema.org `Product` data, when the view has `$metadata` |
| `default/modules/share.pug` | share links for the footer of `site.pug` pages |
| `default/modules/social.pug` | share links of the older `layout.pug` |
## Other ways

**A controller you keep** passes the card to its view: `view('Bookshelf/book', array('book' => $book, 'authors' =>
$authors, 'metadata' => array('title' => $book['title']) + metadata()))`. `Route::page` and `$metadata` in the view replace it.

**The older masters** (`default/master/layoutblocks.pug`, `layout.pug`) print the card only when the view gets
`'metadata'`, and the share links when it also gets `'social' => true`:
`view('default/index', array('metadata' => metadata(), 'social' => true))`.
## Common mistakes

+ **No card at all.** `metadata()` has no `title`: nothing is printed without one.
+ **The image does not show.** The address is relative (`/public/...`) or the server is not reachable from the
  internet: use a full `https://` address of a server online.
+ **An old card keeps showing.** The platform kept it: *Scrape again* in Facebook's debugger.
+ **The per-page title is ignored.** `$metadata` was set outside a block: set it in the first block of the view.
+ **Share links share nothing.** `site_url` is not in `metadata()`.
## Related pages

+ [Search referencing and analytics](https://github.com/caligrafy/caligrafy-quill/wiki/9.4-Search-Referencing-and-Analytics)
+ [Views](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views)
+ [Routing: pages](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing)

<br /><br />
>[Next Section: Learn about Search Referencing and Analytics](https://github.com/caligrafy/caligrafy-quill/wiki/9.4-Search-Referencing-and-Analytics)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.4-Search-Referencing-and-Analytics -->

Search engines read three things Caligrafy helps with: the **description** of each page (the line under its title in
the results), the proof that the site is yours (**Google Search Console**), and, once people come, **Google
Analytics**. The description comes from `metadata()` ([rich cards](https://github.com/caligrafy/caligrafy-quill/wiki/9.3-Metadata-&-Social-Rich-Cards));
analytics is one setting of `.env`.
## With Claude

```text
Make Bookshelf ready for Google: a description for every page, and Google Analytics with the id G-XXXXXXX in production
```

Claude sets the `description` of `metadata()` in `application/config/config.php` and tells you to put
`GOOGLE_ANALYTICS_ID` in the production `.env` (on Caligrafy Cloud: `php caligrafer.php cloud secret set <app>
GOOGLE_ANALYTICS_ID=G-...`). It does not sign in to Google for you.

**Check**

+ The page source has `<meta name="description" ...>`.
+ Online, with `APP_ENV=production`, the source has `googletagmanager.com/gtag/js?id=G-...`; locally it has none.
## By hand

**1. A description for every page.** Set `description` in the `metadata(...)` call of `application/config/config.php`
(the whole call is in [rich cards](https://github.com/caligrafy/caligrafy-quill/wiki/9.3-Metadata-&-Social-Rich-Cards)):

```php
metadata(array(
    'site_name' => 'Bookshelf',
    'title' => 'Bookshelf: your books, lent and returned',
    'description' => 'Know who has your books and when they come back.',
));
```

Every page of `default/master/site` then has
`<meta name="description" content="Know who has your books and when they come back."/>`. A page gets its own
description as in [a card per book](https://github.com/caligrafy/caligrafy-quill/wiki/9.3-Metadata-&-Social-Rich-Cards#card).

**2. Prove the site is yours to Google.** In [Google Search Console](https://search.google.com/search-console), add a
**URL prefix** property with the app's address (`https://bookshelf.example.com`) and choose **HTML file**. Download the
file Google gives (`google<code>.html`), put it at the **root of the project** (next to `index.php`), commit it and
deploy. Apache serves a file that exists as it is, so `https://bookshelf.example.com/google<code>.html` answers the
file; press **Verify**. A **Domain** property is verified with a DNS record at your domain's registrar instead.

**3. Google Analytics.** Create a Google Analytics property and copy its measurement id (`G-...`). In the `.env` of
the production server:

```text
APP_ENV=production
GOOGLE_ANALYTICS_ID=G-XXXXXXX
```

Every page of `default/master/site` then loads `https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX`. With
`APP_ENV=local` the tag is never printed, so your own visits while you develop are not counted.

**Check**

+ The source of `/` has the description.
+ Search Console says *Ownership verified*.
+ Online, the source has the `gtag` script with your id; Analytics shows your visit in its real-time view.
## Reference

| What | Where it comes from | Printed by |
|---|---|---|
| `<meta name="description">` | `metadata()`'s `description`, or the view's `$metadata` | `default/modules/metadata.pug`, in every master |
| Google Analytics (`gtag`) | `GOOGLE_ANALYTICS_ID`, only with `APP_ENV=production` | `site.pug` always; `layoutblocks.pug` when the view gets `'google_analytics' => true` |
| `keywords()` | `keywords('books, lending')` | not printed in pages; given to Vue apps as `env.keywords` |
| Search Console proof | an HTML file at the root of the project, or DNS | Apache, as a file |

+ `keywords($value)` keeps a string of keywords for the request and returns it. Google ignores the `keywords` meta tag,
  so the masters do not print one.
+ The layouts print no `google-site-verification` meta tag: use the HTML file or DNS.
+ Files at the root of the project, such as `robots.txt` or a `sitemap.xml` you write, are served as they are, except
  dotfiles, `caligrafer.php`, `composer.*`, `docker-compose.yaml`, `package*.json` and `.sql`, `.log`, `.bak`, `.ini`,
  `.sh`, `.env` files, which `.htaccess` denies.
## Other ways

**The older masters.** A view on `default/master/layoutblocks.pug` gets analytics only when its route passes it:
`view('default/index', array('metadata' => metadata(), 'google_analytics' => true))`. Pages on `site.pug` need nothing.
## Common mistakes

+ **No analytics online.** `APP_ENV` is not `production`, or `GOOGLE_ANALYTICS_ID` is empty in the server's `.env`
  (on Caligrafy Cloud, set it with `cloud secret set`, then deploy).
+ **The verification file answers the app's 404.** It is in `public/` or `application/`: put it at the root of the
  project.
+ **Search results show an old description.** Google reads the page again on its own schedule: ask for a new crawl in
  Search Console (URL inspection).
## Related pages

+ [Metadata and social rich cards](https://github.com/caligrafy/caligrafy-quill/wiki/9.3-Metadata-&-Social-Rich-Cards)
+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)

<br /><br />
>[Next Section: Learn about Security and Upgrading](https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online -->

You built your capabilities, pages and apps on your computer. This page puts the same project online: one production
image (the `Dockerfile` of every project), one command that prepares the database at each start
(`php caligrafer.php deploy`), and two ways to run it, [Caligrafy Cloud](#cloud) (`https://<name>.caligrafy.com`, a
free first half hour) or [your own server](#ownserver). Since Caligrafy Quill 2.4.0.

**Since 2.26.0** the production image tunes itself to its container (processes, database connections, preloading, a response cache): see [performance and deployment](https://github.com/caligrafy/caligrafy-quill/wiki/Performance-and-Deployment). An app that uses an optional SDK (payments, push, passkeys, Groq, the assistant with Claude) must have added it with `php caligrafer.php add <feature>` and committed `composer.lock`.
## With Claude

| You want | Ask |
|---|---|
| the app online at `https://<name>.caligrafy.com` | `/caligrafy-quill:ship bookshelf` |
| a readiness check only, or your own server | `/caligrafy-quill:deploy` or `/caligrafy-quill:deploy --own-server` |
| to sell the app on the marketplace of caligrafy.com | `/caligrafy-quill:marketplace bookshelf` |

`/caligrafy-quill:ship` commits, creates the GitHub repository and pushes (your SSH key, else HTTPS with the GitHub
CLI, else a code to approve in your browser), signs in to Caligrafy Cloud with an approval in your browser (no token
to copy), creates the app, adds its deploy key, deploys it and checks it online. You approve in your browser, and say
yes before credits are spent. `/caligrafy-quill:deploy --own-server` prepares the project for Coolify or Docker and
deploys nothing: the server is yours.

**Check**

+ `docker compose exec dev-box php caligrafer.php cloud status bookshelf` says `running`, with the time left.
+ `https://bookshelf.caligrafy.com` opens; sign-in and a form work there.
+ `git ls-files` lists no `.env`, `.env.php` or `.env.production`.
## By hand: Caligrafy Cloud

Run these commands on your computer, in the project's folder, with its Docker server up (without Docker, drop
`docker compose exec dev-box`). Run on the Docker server, `cloud login` cannot open your browser: open the address it
prints.

**1. Check the project.**

```bash
docker compose exec dev-box php caligrafer.php version                        # 2.4.0 or later
ls Dockerfile Dockerfile.dockerignore composer.lock
git ls-files | grep -E '(^|/)\.env($|\.)' | grep -v '\.env\.example$' | grep -v '^framework/settings/'   # must print nothing
docker compose exec dev-box php caligrafer.php doctor --only project          # no FAIL
```

Every `application/models/<folder>/create_db.sql` must be safe to run again (`CREATE TABLE IF NOT EXISTS`, no `DROP`
or `DELETE`). `composer.lock` must be committed. The project's `.gitignore` already leaves out `.env`, `.env.php` and,
since 2.19.1, every other `.env.*` file (`.env.testing`, `.env.production`...) except `.env.example`. A single page
application made with `php caligrafer.php create` is online only once built: run `npm run build` in `public/<name>`
and commit its `dist/` folder (the image does not run `npm`; since 2.19.1 the template no longer ignores `dist/`).

**2. An account.** Create it at [deploy.caligrafy.com](https://deploy.caligrafy.com/signup) (your email is your
username; the same account signs in to caligrafy.com) and open the link of the confirmation email.

**3. Your code on GitHub.** Commit and push the project, with its `Dockerfile`:

```bash
git add -A
git commit -m "Bookshelf"
git push
```

**4. Sign in, create the app, deploy.**

```bash
docker compose exec dev-box php caligrafer.php cloud login                 # approve, in the browser page it opens, the code it shows
docker compose exec dev-box php caligrafer.php cloud create bookshelf      # the repository of this project (git origin), branch main
docker compose exec dev-box php caligrafer.php cloud deploy bookshelf      # builds and starts it, and follows the build
```

A **private** repository needs the app's read-only deploy key: `cloud create` saves it in
`.caligrafy/bookshelf-deploy-key.pub`; add it with
`gh repo deploy-key add .caligrafy/bookshelf-deploy-key.pub -R <owner>/<repo> --title "Caligrafy Cloud"` (or in GitHub,
*Settings, Deploy keys*, *Allow write access* off) before `cloud deploy`.

**5. The settings of your services.** The database settings, the keys, `APP_URL` and `LEGACY_API_KEY=false` are
written for the app. Set the others, then deploy again:

```bash
docker compose exec dev-box php caligrafer.php cloud secret set bookshelf PAY_PRIVATE_KEY_PRODUCTION=sk_live_...
docker compose exec dev-box php caligrafer.php cloud secret set bookshelf STRIPE_WEBHOOK_SECRET=whsec_...
docker compose exec dev-box php caligrafer.php cloud deploy bookshelf
```

**6. Check it.** Open `https://bookshelf.caligrafy.com`, sign in, send a form. Then:

```bash
docker compose exec dev-box php caligrafer.php cloud status bookshelf      # running, the time left
docker compose exec dev-box php caligrafer.php cloud logs bookshelf        # the deploy step's lines, then what the app prints
docker compose exec dev-box php caligrafer.php cloud jobs bookshelf        # the scheduled jobs, their last and next runs
```

The log of a start shows the deploy step:

```text
 Caligrafy deploy
  OK    Settings: .env compiled to .env.php (read without parsing on every request)
  OK    Framework tables: tokens, audit log, job runs, jobs, cache, migrations, scripts
  OK    application/models/Auth/create_db.sql: run
  OK    application/models/Bookshelf/create_db.sql: run
  OK    application/models/Loans/create_db.sql: run
```

**7. Keep it online.** The first 30 minutes are free; then add time:

```bash
docker compose exec dev-box php caligrafer.php cloud credits 10            # opens the Stripe payment page
docker compose exec dev-box php caligrafer.php cloud extend bookshelf month   # 5 credits; a paused app starts again
```

**Check**

+ `cloud status` says `running`.
+ The pages, the sign-in and a form work online.
+ `cloud jobs` lists your scheduled jobs, if the app has some.
## <a name="image"></a>Reference: the production image

Every project has a `Dockerfile` at its root. Hosts that build from a Dockerfile use it as it is:

+ PHP 8.5 and Apache (`mod_rewrite`, `mod_headers`), with the extensions Caligrafy uses (`bcmath`, `exif`, `gd`, `intl`,
  `mysqli`, `pdo_mysql`, `zip`) and the production `php.ini`;
+ the libraries of your `composer.lock`, without the development packages;
+ no Node.js and no `npm`: client apps are served as they are in the repository (a Vite app from its committed `dist/`);
+ your code, without what must not be online: `Dockerfile.dockerignore` leaves out `.env` and `.env.*` (but
  `.env.example`), `.git`, `vendor`, `node_modules`, `qa`, `tests`, `backups`, the Claude plugin, `public/uploads/*` and
  `.caligrafy`;
+ PHP sessions in `/var/lib/php/sessions`: a volume there keeps people signed in across deploys;
+ at start, `php caligrafer.php deploy --wait ${CALIGRAFY_DEPLOY_WAIT:-60}`, then Apache (a database that is not ready
  does not keep the site down).

**Settings are not in the image.** The running container reads its `.env` as a file at `/var/www/html/.env`, not plain
environment variables: the host must let you mount a file. In production it has `APP_ROOT=` (empty), `APP_ENV=production`,
`APP_DEBUG=false`, `APP_PROTOCOL=https`, its own `APP_KEY` and `API_KEY` (`php caligrafer.php generatekeys`),
`DB_ACTIVATE=true` and the production `DB_*`, and the keys of your services. The list and the reasons are in
[Security: the production settings](https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading).

`docker/Dockerfile` is another file: the development image of `docker-compose.yaml`.

## <a name="deploy"></a>Reference: `php caligrafer.php deploy`

What the image runs before Apache starts:

1. prints the scheduled jobs on one line (`caligrafy-schedule {...}`), which Caligrafy Cloud reads;
2. compiles `.env` to `.env.php` (2.19.0): pages then read the settings without parsing `.env` (`env cache`); a `.env`
   changed later is read as it is until the next start;
3. waits for the database (60 seconds by default, `--wait <seconds>` or `CALIGRAFY_DEPLOY_WAIT`);
4. creates the framework tables (tokens, the audit log, job runs, notifications, jobs, the cache, migrations), safe to
   run again;
5. runs every `application/models/<folder>/create_db.sql` that is **new or changed** since its last run, in folder
   order, and records it in `caligrafy_scripts`;
6. runs the [migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations) of `application/migrations`
   that never ran on this database, in order (2.18.0).

+ A changed script that drops, deletes or truncates (`DROP TABLE`, `DELETE FROM`, `TRUNCATE`...) is never run again on
  its own: the log says so, and you run it by hand when you mean it (`php caligrafer.php sql <file>`). `seed.sql` and
  other scripts are never run. Without `DB_ACTIVATE=true` there is nothing to do for the database.
+ A statement that adds a column, an index or a foreign key already there is skipped, so a `create_db.sql` keeps its
  `ALTER TABLE ... ADD` lines. Change a table that holds data with a migration.
+ It exits with `1` when the database could not be prepared, after saying why.

```bash
php caligrafer.php deploy                 # what the image runs at start
php caligrafer.php deploy --wait 120      # wait up to 2 minutes for the database
```

## <a name="cloud"></a>Reference: Caligrafy Cloud

[Caligrafy Cloud](https://deploy.caligrafy.com) builds your project from its GitHub repository and gives it a MySQL
database, its keys and an address: `https://<name>.caligrafy.com`.

| | |
| --- | --- |
| Free time | every new app is free for its first 30 minutes online, from its first deploy |
| Credits | 1 credit = 1 USD, in packs of 5, 10, 25 or 50, paid with Stripe |
| Time online | a week: 2 credits; a month: 5; a year: 50. Time is added to what is left |
| When the time ends | the app is paused (its address shows a paused page) and you get an email. Its data is kept 7 days, then deleted |
| Limits | 5 apps per account, 256 MB of memory and a quarter of a CPU per app |

| Command | What it does |
|---|---|
| `cloud login [--no-browser]` | prints a code and opens `https://deploy.caligrafy.com/cli?code=...`: approve it there. `--token cq_...` or `--paste` take a token of the dashboard. The token is kept in `.caligrafy/cloud.json` (ignored by git); `CALIGRAFY_CLOUD_TOKEN` overrides it |
| `cloud account` | your email and credits |
| `cloud create <name> [--repo <url>] [--branch <b>]` | the app, from this project's GitHub repository |
| `cloud key <name>` | the read-only deploy key of a private repository |
| `cloud deploy <name> [--no-wait]` | builds and starts it |
| `cloud apps`, `cloud status <name>`, `cloud logs <name> [--jobs]` | your apps, one app's state and time left, its logs |
| `cloud jobs <name> [run <job> \| history <job>]` | its scheduled jobs, one run now, a job's runs |
| `cloud secret set <name> KEY=value`, `secret list <name>`, `secret delete <name> KEY` | a setting of its `.env`, applied at the next deploy; stored encrypted, never shown again |
| `cloud extend <name> week\|month\|year` | 2, 5 or 50 credits (an account with no limit spends none and its apps have no end date) |
| `cloud credits 5\|10\|25\|50` | buy credits on Stripe |
| `cloud submit <name> [--no-deploy]` | sends the marketplace listing, then deploys |
| `cloud delete <name> --yes` | the app, its database and files, for good |
| `cloud logout` | |

+ Every `cloud` command exits with `1` when Caligrafy Cloud refuses; a pipe (`| tail`) hides it.
+ The database settings and the keys of the app are written for you, and your settings cannot replace them;
  `APP_ENV=production` and `APP_DEBUG=false` are the defaults.
+ **Pages online.** Caligrafy Cloud turns the shared legacy API key off (`LEGACY_API_KEY=false`). Pages call their
  routes with the session and its CSRF token (`apiHeaders()`, the generated JS client); a page that still sends the key
  gets `[ERROR 1004] Access Denied: the legacy API key is turned off`. Programs and agents use
  [personal access tokens](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP).
+ **A password until it is on the marketplace.** The app's page has a *Password* section that locks the app with a
  password you share (off by default). Everyone types it once per browser; it lasts 30 days. While locked, pages send
  visitors to `https://deploy.caligrafy.com/unlock/<name>`, API and agent calls get `401`, and `cloud apps` and
  `cloud status` print `[password protected]`. Locking or unlocking restarts the app (2 to 5 minutes). Offering the app
  to the marketplace removes the password for good.
+ **AI agents.** Caligrafy Cloud is itself a Caligrafy application: an agent connects to
  `https://deploy.caligrafy.com/mcp` with a token of the dashboard (*Command line and AI agents*) and can list, deploy
  and extend your apps.
+ Every command is also in [Caligrafer: cloud](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#cloud).

## <a name="marketplace"></a>Selling your app on the marketplace

An app online on Caligrafy Cloud can be offered on the [marketplace of caligrafy.com](https://caligrafy.com/marketplace):
Caligrafy sells a prompt that recreates it with Caligrafy, using Claude, and you earn 25% of every sale.

1. On the app's page in the App console (deploy.caligrafy.com), **Marketplace**: say where we pay you (your country;
   wire details where Stripe does not pay out), then **Offer it to the marketplace**.
2. In Claude Code, in the app's folder, run `/caligrafy-quill:marketplace bookshelf`. It reads the whole code, runs the
   app on your computer and walks through it to screenshot its key features (5 at most), writes the title, the
   description, the prompt that recreates the app and an estimated price window in one private file,
   `.caligrafy/marketplace.json` (ignored by git), then sends it to Caligrafy and redeploys the app. It often takes 15 to
   30 minutes. Without Claude Code, write the file yourself and send it: `php caligrafer.php cloud submit bookshelf`.
3. Caligrafy reviews the listing, sets the final price and publishes it, or turns it down with a reason (offer it again
   after the changes). On caligrafy.com, **Listings** follows each listing (offered, to fix, published), **Earnings** its
   sales and your payouts (from 50 USD, once a month, 14 days after each sale), and **Tasks** what waits for you.

Each app on Explore comes three ways: its **prompt**, which recreates it with Caligrafy, using Claude; its **code**,
reproduced from the prompt into a private GitHub repository of the buyer; or **managed for you**, online at
`<name>.caligrafy.com` for a monthly or yearly price. You earn 25% of the prompt's price on each of them. What people buy
is in **Library** (prompts and code), and managed apps are in **Apps** (the App console), under *Managed for you*.

**Submitting an idea.** No code at all: on [caligrafy.com/ideas/new](https://caligrafy.com/ideas/new), describe the app
(what it does, who it is for, its powers) and get an estimate, free. Caligrafy reviews it, builds a proof of concept and
gives it to you to try, privately, for 3 days; ask for fixes once, then take it in one of the three ways or drop it.
Your ideas are in **Ideas** on caligrafy.com.

## <a name="ownserver"></a>Your own server

The same image runs on any host that builds a Dockerfile and lets you give it a file and a database.

+ **[Coolify](https://coolify.io)** (open source, on your own server): a *Dockerfile* application from your repository,
  a MySQL database, the `.env` as a *file storage* mounted at `/var/www/html/.env`, and volumes at
  `/var/www/html/public/uploads` and `/var/lib/php/sessions`. MySQL 8.4 with its defaults needs more than 256 MB of
  memory: give the database more, or a smaller configuration.
+ **Any server with Docker:**

```bash
docker build -t bookshelf .
docker run -d -p 80:80 \
  -v "$(pwd)/.env.production:/var/www/html/.env:ro" \
  -v bookshelf-uploads:/var/www/html/public/uploads \
  -v bookshelf-sessions:/var/lib/php/sessions \
  bookshelf
```

Put HTTPS in front of it (a load balancer, Coolify's proxy, Caddy...). Hosts that offer only environment variables and
no file (Railway, Render, DigitalOcean App Platform) are not supported yet.

**Without Docker** (files copied to a PHP 8.3+ server with Apache): run `php caligrafer.php env cache` after each change
to `.env` (never commit `.env.php`), and `php caligrafer.php deploy` for the database. After copying files that keep
their old modification times (`rsync -a`, `cp -p`), run `php caligrafer.php cache clear`: it empties the compiled views
and the class map (which otherwise finds new classes by itself within a minute with `APP_ENV=production`).

**Scheduled jobs** ([Scheduled jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs)): run a second
container from the same image and `.env` with `php caligrafer.php schedule work` (on Coolify, a second application with
that start command), or `php caligrafer.php schedule due` from the server's cron every minute. One of the two.

**Background jobs** ([Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs)): a job on
`queue_work` in `schedule.php` runs them with the scheduler, or a container of its own runs `php caligrafer.php queue
work` for longer jobs.

**Notifications:** the web push keys made once (`php caligrafer.php notify keys --subject https://<the address>`) and
kept across deploys, `APP_URL`, `MAIL_*`, and HTTPS.
## <a name="troubleshooting"></a>Common mistakes

| You see | Why, and what to do |
| --- | --- |
| The build fails | `cloud logs <name>` shows the build: usually `composer.lock` missing or out of date (`composer update`, commit the lock file) |
| `caligrafer deploy: the database is not prepared` | the line above it says why: the database is not reachable (the `DB_*` settings, or `--wait` longer), or a SQL error in a `create_db.sql` or a migration (it names the statement that failed) |
| `Host ... is not allowed to connect` | the database was created but its user was not: on your own server, create the database again (it has no data yet) |
| Caligrafy Cloud cannot read a private repository | the deploy key is not added on GitHub |
| The address shows a paused page | its time ended (`cloud extend <name> week`), or it is deploying, or there is no app with that name |
| `deploy` answers *has no time left (its free 30 minutes are used)* | `cloud extend <name> week` (2 credits), then deploy again; `cloud credits 5` to buy credits |
| The page works locally, its calls get `[ERROR 1004] Access Denied` online | the page sends the legacy API key, off on Caligrafy Cloud: call the routes with `apiHeaders()` or the JS client. A single page application made before 2.19.1 sends `VITE_API_KEY`: give it the session headers of the 2.19.1 template (`apiHeaders()` of `src/common/app.js`) |
| `cloud login` waits and nothing opens | it runs in the Docker server: open the address it printed, approve the code |
| Everyone is signed out after a deploy | no volume at `/var/lib/php/sessions` |
| Uploaded files disappear after a deploy | no volume at `/var/www/html/public/uploads` |
| Pages are slow online | `APP_DEBUG=true` in the production `.env` |
| A setting changed on your own server seems ignored | run `php caligrafer.php env cache` again (or restart the container: the deploy step compiles `.env`) |
## Related pages

+ [Security and upgrading](https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading)
+ [Caligrafer: cloud, deploy, env](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#cloud)
+ [Migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations)
+ [Scheduled jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs)
+ [Claude Code plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Deploying-to-Caligrafy-Cloud -->

[Caligrafy Cloud](https://deploy.caligrafy.com) puts a project online at `https://<name>.caligrafy.com`: it builds the
project from its GitHub repository with its own `Dockerfile`, gives it a MySQL database, its keys, its `.env` and the
volumes it needs, and runs its scheduled jobs. Every new app is free for its first 30 minutes online. Since 2.4.0.
## With Claude

```text
/caligrafy-quill:ship bookshelf
```

It commits, creates the GitHub repository and pushes (your SSH key, else HTTPS with the GitHub CLI, else a code to
approve in your browser), signs in to Caligrafy Cloud with an approval in your browser, creates the app, adds its deploy
key, deploys it and checks it online. You approve in the browser, and say yes before credits are spent.

**Check** before you say OK:
+ `php caligrafer.php cloud status bookshelf` says `running`, with the time left;
+ `https://bookshelf.caligrafy.com` opens; sign-in and a form work there;
+ `git ls-files` lists no `.env`, `.env.php` or `.env.production`.
## By hand

Run the commands on your computer, in the project's folder, with its Docker server up (without Docker, drop
`docker compose exec dev-box`).

**1. Check the project.**

```bash
docker compose exec dev-box php caligrafer.php version                        # 2.4.0 or later
ls Dockerfile Dockerfile.dockerignore composer.lock
git ls-files | grep -E '(^|/)\.env($|\.)' | grep -v '\.env\.example$' | grep -v '^framework/settings/'   # must print nothing
docker compose exec dev-box php caligrafer.php doctor --only project          # no FAIL
```

Every `create_db.sql` must be safe to run again ([The deploy step](https://github.com/caligrafy/caligrafy-quill/wiki/The-Deploy-Step#scripts)),
`composer.lock` committed, and a Vite single page application built (`npm run build` in `public/<name>`, `dist/`
committed).

**2. An account.** Create it at [deploy.caligrafy.com](https://deploy.caligrafy.com/signup) (your email is your
username; the same account signs in to caligrafy.com) and open the link of the confirmation email.

**3. Your code on GitHub.**

```bash
git add -A
git commit -m "Bookshelf"
git push
```

**4. Sign in.**

```bash
docker compose exec dev-box php caligrafer.php cloud login
```

```text
 To sign in, approve this code in your browser: <code>
 https://deploy.caligrafy.com/cli?code=...
```

Open the address (in the Docker server the browser does not open by itself), check that the code is the same, approve.
The command then prints ` Signed in as you@example.com (... credits). The token is in .caligrafy/cloud.json (git-ignored).`

**5. Create the app.**

```bash
docker compose exec dev-box php caligrafer.php cloud create bookshelf
```

```text
 Created https://bookshelf.caligrafy.com from https://github.com/you/bookshelf (main).
 Next: php caligrafer.php cloud deploy bookshelf
```

It reads the repository from the project's `origin` remote (`--repo <url>` names another, `--branch <b>` another
branch). A **private** repository gets a read-only deploy key, printed and saved in
`.caligrafy/bookshelf-deploy-key.pub`: add it on GitHub before deploying,

```bash
gh repo deploy-key add .caligrafy/bookshelf-deploy-key.pub -R <owner>/<repo> --title "Caligrafy Cloud"
```

or in the repository's *Settings, Deploy keys*, with *Allow write access* off.

**6. Its settings.** The database settings, the keys, `APP_URL`, `APP_ENV=production`, `APP_DEBUG=false` and
`LEGACY_API_KEY=false` are written for the app. Add the keys of your services:

```bash
docker compose exec dev-box php caligrafer.php cloud secret set bookshelf PAY_PRIVATE_KEY_PRODUCTION=sk_live_...
docker compose exec dev-box php caligrafer.php cloud secret list bookshelf
```

Each one is stored encrypted, never shown again, and applied at the next deploy.

**7. Deploy.**

```bash
docker compose exec dev-box php caligrafer.php cloud deploy bookshelf
```

```text
 Deploying https://bookshelf.caligrafy.com (a few minutes)...
 Online: https://bookshelf.caligrafy.com
```

It follows the build for up to 15 minutes (`--no-wait` returns at once). A failed build prints the last 30 lines of
its log.

**8. Check it.** Open `https://bookshelf.caligrafy.com`, sign in, send a form. Then:

```bash
docker compose exec dev-box php caligrafer.php cloud status bookshelf      # running, the time left
docker compose exec dev-box php caligrafer.php cloud logs bookshelf        # the deploy step, then what the app prints
docker compose exec dev-box php caligrafer.php cloud jobs bookshelf        # the scheduled jobs, their last and next runs
```

**9. Keep it online.** After the free 30 minutes, add time:

```bash
docker compose exec dev-box php caligrafer.php cloud credits 10               # prints the Stripe page to pay on
docker compose exec dev-box php caligrafer.php cloud extend bookshelf month   # 5 credits; a paused app starts again
```
## <a name="reference"></a>Reference

| | |
| --- | --- |
| Free time | every new app, its first 30 minutes online from its first deploy |
| Credits | 1 credit = 1 USD, in packs of 5, 10, 25 or 50, paid with Stripe |
| Time online | a week: 2 credits; a month: 5; a year: 50; added to what is left |
| When the time ends | the app is paused (its address shows a paused page) and you get an email; its data is kept 7 days, then deleted |
| Limits | 5 apps per account, 256 MB of memory and a quarter of a CPU per app |
| Settings | `.env` written by Cloud, with your `cloud secret` values; yours cannot replace the database settings and keys |
| Scheduled jobs | read at each deploy from the `caligrafy-schedule` line of the deploy step; `cloud jobs` shows them |
| Sign-in for the command line | `.caligrafy/cloud.json`, or `CALIGRAFY_CLOUD_TOKEN`; `CALIGRAFY_CLOUD_URL` for another service |
| AI agents | `https://deploy.caligrafy.com/mcp` with a token of the dashboard (*Command line and AI agents*): list, deploy and extend your apps |

Every `cloud` command is on [Caligrafer: deploy commands](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer-Deploy-Commands#cloud).

**A password until it is on the marketplace.** The app's page has a *Password* section that locks the app with a
password you share (off by default). Each browser types it once, for 30 days. While locked, pages send visitors to
`https://deploy.caligrafy.com/unlock/<name>`, API and agent calls get `401`, and `cloud apps` and `cloud status` print
`[password protected]`. Locking or unlocking restarts the app (2 to 5 minutes). Offering the app to the marketplace
removes the password for good ([Selling your app](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online#marketplace)).
## Common mistakes

| You see | Why, and what to do |
| --- | --- |
| The build fails | `cloud logs <name>`: usually `composer.lock` missing or out of date (G69): `composer update`, commit it |
| Cloud cannot read a private repository | the deploy key is not added on GitHub (`cloud key <name>` prints it again) |
| `deploy` answers *has no time left (its free 30 minutes are used)* | `cloud extend <name> week` (2 credits), then deploy again (G90) |
| `cloud deploy ... \| tail` says nothing went wrong | a pipe hides the exit code (G89): run it whole |
| Pages work locally, their calls get `[ERROR 1004] Access Denied` online | the legacy API key is off on Cloud (G87): call the routes with `apiHeaders()` or the JS client |
| The address shows a paused page | its time ended, it is deploying, or there is no app with that name |
| `cloud login` waits and nothing opens | it runs in the Docker server: open the address it printed |
| Stripe emails about failing test-mode webhooks once live | a test-mode endpoint still points at the production address (G115): create the endpoint in live mode, set its `whsec_...` as `STRIPE_WEBHOOK_SECRET`, and remove the test one |
## Related pages

+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)
+ [The production image](https://github.com/caligrafy/caligrafy-quill/wiki/The-Production-Image) · [The deploy step](https://github.com/caligrafy/caligrafy-quill/wiki/The-Deploy-Step)
+ [Deploying to your own server](https://github.com/caligrafy/caligrafy-quill/wiki/Deploying-to-Your-Own-Server)
+ [Caligrafer: deploy commands](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer-Deploy-Commands)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Deploying-to-Your-Own-Server -->

The [production image](https://github.com/caligrafy/caligrafy-quill/wiki/The-Production-Image) of a project runs on
any host that builds a Dockerfile and lets you give the container a file and a database: Coolify on your own server, or
any server with Docker. A PHP server without Docker works too. This page sets up each one, with the scheduled jobs, the
background jobs and the notifications. Since 2.4.0.
## With Claude

```text
/caligrafy-quill:deploy --own-server
```

It checks that the project is ready, writes `.env.production` for the host with your OK (its own keys from
`generatekeys`, `DB_ACTIVATE=true` and the production `DB_*`; never committed), and says what to set up on the host. It deploys nothing:
the server is yours.

**Check** before you say OK: `curl -I https://<your-host>/.env` answers `403` or `404`, and sign-in and a form work.
## By hand

### <a name="coolify"></a>Coolify

[Coolify](https://coolify.io) is open source and runs on your own server.

1. A **MySQL** database resource. MySQL 8.4 with its defaults needs more than 256 MB of memory (G71): give it more, or
   a smaller configuration (`performance_schema = OFF`, `innodb_buffer_pool_size = 64M`, about 384 MB).
2. A **Dockerfile** application from your repository (it uses the `Dockerfile` at the root).
3. The production `.env` as a **file storage** mounted at `/var/www/html/.env`, with the database's host, name, user
   and password in `DB_*` and `DB_ACTIVATE=true`.
4. Two **volumes**: `/var/www/html/public/uploads` and `/var/lib/php/sessions`.
5. Deploy. The application's log starts with [the deploy step](https://github.com/caligrafy/caligrafy-quill/wiki/The-Deploy-Step).

Coolify's proxy gives it HTTPS.

### <a name="docker"></a>Any server with Docker

```bash
docker build -t bookshelf .
docker run -d -p 80:80 \
  -v "$(pwd)/.env.production:/var/www/html/.env:ro" \
  -v bookshelf-uploads:/var/www/html/public/uploads \
  -v bookshelf-sessions:/var/lib/php/sessions \
  bookshelf
```

Put HTTPS in front of it (a load balancer, Caddy...). `-e CALIGRAFY_DEPLOY_WAIT=120` gives a database that starts
slowly two minutes.

### <a name="nodocker"></a>Without Docker

Files copied to a PHP 8.3+ server with Apache (`mod_rewrite`, `AllowOverride FileInfo` or `All` for the `.htaccess`
files) and the extensions the image has (`bcmath`, `exif`, `gd`, `intl`, `mysqli`, `pdo_mysql`, `zip`):

```bash
composer install --no-dev
php caligrafer.php env cache      # after each change to .env (never commit .env.php)
php caligrafer.php deploy         # the database: framework tables, scripts, migrations
php caligrafer.php cache clear    # after copying files that keep their old modification times (rsync -a, cp -p)
```

`cache clear` empties the compiled views and the class map; with `APP_ENV=production` the class map otherwise finds new
classes by itself within a minute (G117). On nginx, write the rules of the `.htaccess` files yourself: they deny
dotfiles, the server-side folders and scripts in `public/uploads`.
## <a name="jobs"></a>Scheduled jobs, background jobs, notifications

+ **Scheduled jobs** ([Scheduled jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs)): one of the
  two, not both:
  + a second container from the same image and `.env`, with the command `php caligrafer.php schedule work` (on Coolify,
    a second application with that start command);
  + or the server's cron, every minute: `* * * * * cd /var/www/html && php caligrafer.php schedule due`.
+ **Background jobs** ([Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs)): a job of
  `application/config/schedule.php` on the framework's `queue_work` capability runs them with the scheduler; for longer
  jobs, a container of its own runs `php caligrafer.php queue work`.
+ **Notifications** ([Notifications](https://github.com/caligrafy/caligrafy-quill/wiki/Notifications)): the web push
  keys made once (`php caligrafer.php notify keys --subject https://<the address>`) and kept across deploys, `APP_URL`,
  the `MAIL_*` settings, and HTTPS.
## <a name="checklist"></a>Before you open it to people

+ `APP_ENV=production`, `APP_DEBUG=false`, `APP_ROOT=` (empty), `APP_PROTOCOL=https`, keys of its own
  (`php caligrafer.php generatekeys`).
+ `curl -I https://<your-host>/.env` answers `403` or `404`.
+ Personal access tokens for programs and agents, then `LEGACY_API_KEY=false`.
+ `php caligrafer.php doctor --env .env.production` from your computer, when it can reach the database.

The whole list, and why: [the production checklist](https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading#checklist).
## Common mistakes

| You see | Why, and what to do |
| --- | --- |
| The settings are ignored | the host gives environment variables, not a file (G67): mount the `.env` at `/var/www/html/.env`. Railway, Render and DigitalOcean App Platform are not supported yet |
| `Host ... is not allowed to connect` | MySQL was killed while it initialized (G71): more memory, then recreate its volume while it has no data |
| Everyone is signed out after a deploy | no volume at `/var/lib/php/sessions` (G70) |
| Uploaded files disappear after a deploy | no volume at `/var/www/html/public/uploads` (G70) |
| A changed view still shows the old page | files copied with old modification times (G117): `php caligrafer.php cache clear` |
| A job's `Cache::forget()` does not reach the pages | `CACHE_STORE=file`: the web server and the command line have their own folders (G119). Keep the `database` store |
| Jobs run twice | both a `schedule work` container and a cron line |
| A setting changed on the server seems ignored | run `php caligrafer.php env cache` again, or restart the container |
## Related pages

+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)
+ [The production image](https://github.com/caligrafy/caligrafy-quill/wiki/The-Production-Image) · [The deploy step](https://github.com/caligrafy/caligrafy-quill/wiki/The-Deploy-Step)
+ [Deploying to Caligrafy Cloud](https://github.com/caligrafy/caligrafy-quill/wiki/Deploying-to-Caligrafy-Cloud)
+ [Security and upgrading](https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/The-Production-Image -->

Every Caligrafy project has a **production image**: the `Dockerfile` at its root. Caligrafy Cloud, Coolify and any
host that builds from a Dockerfile use it as it is. This page says what is in it, what is left out, what runs when it
starts, and what the container needs from the host. Since 2.4.0.

**Since 2.26.0** the image starts with `docker/production/start.sh`: it sizes Apache to the container (`PHP_PROCESSES`), turns keep-alive off, keeps database connections, preloads the framework, compiles the views, keeps public answers in memory and can run the async server (`ASYNC=on`). Every setting is on [performance and deployment](https://github.com/caligrafy/caligrafy-quill/wiki/Performance-and-Deployment).

> `docker/Dockerfile` is another file: the development image of `docker-compose.yaml` (the `dev-box` and `scheduler`
> containers).
## With Claude

```text
/caligrafy-quill:deploy
```

The `deploy` skill checks that the project is ready for the image (the `Dockerfile`, `composer.lock`, no `.env` in git,
safe `create_db.sql` scripts, a built SPA) and says what to fix. It deploys nothing.

**Check** before you say OK: `docker build -t myapp .` finishes, and `git ls-files` lists no `.env`, `.env.php` or
`.env.production`.
## By hand

Build and run the image on your computer, with a production-like `.env` of your own:

```bash
docker build -t bookshelf .
docker run --rm -p 8090:80 -v "$(pwd)/.env.production:/var/www/html/.env:ro" bookshelf
```

The container's log starts with the [deploy step](https://github.com/caligrafy/caligrafy-quill/wiki/The-Deploy-Step),
then Apache's. A `.env.production` whose database cannot be reached prints
` FAIL  Database: not reachable after 60 s: check the DB_* settings` and
`caligrafer deploy: the database is not prepared (see above)`, and the site starts anyway.
## <a name="contents"></a>What is in it

| Layer | What the `Dockerfile` does |
| --- | --- |
| Base | `php:8.5-apache` |
| System | Debian packages over `https`, the libraries for `gd`, `zip` and `intl`, `unzip` and `git`; Apache's `rewrite` and `headers` modules |
| PHP | the extensions `bcmath`, `exif`, `gd` (FreeType, JPEG), `intl`, `mysqli`, `pdo_mysql` and `zip`; the production `php.ini` |
| Sessions | `session.save_path = "/var/lib/php/sessions"`, a folder owned by `www-data` |
| Libraries | Composer 2, then `composer install --no-dev --no-interaction --prefer-dist --no-scripts --no-autoloader --no-plugins` from `composer.json` and `composer.lock` alone, so a code change does not install them again |
| Code | `COPY . .` (less what `Dockerfile.dockerignore` leaves out), `composer dump-autoload --optimize --no-dev --no-plugins`, `public/uploads` and `backups/` created, `public/uploads` owned by `www-data` |
| Port | `80` |

No Node.js and no `npm`: client apps are served as they are in the repository, a Vite app from its committed `dist/`.
Composer runs with `--no-plugins` (2.22.1), so no Composer plugin tries to run `npm` during the build.
## <a name="ignore"></a>What is left out

`Dockerfile.dockerignore` keeps these out of the image:

| Left out | Why |
| --- | --- |
| `.env`, `.env.*` (but `.env.example`) | secrets: the host gives the settings |
| `.git`, `.github` | history and CI |
| `vendor`, `**/node_modules` | installed in the image, or not needed |
| `qa`, `tests`, `backups` | development, tests and update backups |
| `claude-plugin`, `.claude`, `.claude-plugin`, `framework/design` | tools for Claude Code and the design styles' sources |
| `*.log`, `.DS_Store` | |
| `public/uploads/*` (but its `.gitignore`) | uploads live in a volume |
| `.caligrafy` | the Cloud sign-in and the marketplace listing |
## <a name="start"></a>What runs at start

```sh
php caligrafer.php deploy --wait ${CALIGRAFY_DEPLOY_WAIT:-60} || echo 'caligrafer deploy: the database is not prepared (see above)'; exec apache2-foreground
```

1. [`php caligrafer.php deploy`](https://github.com/caligrafy/caligrafy-quill/wiki/The-Deploy-Step): the scheduled jobs
   line, `.env` compiled to `.env.php`, then the database (it waits up to `CALIGRAFY_DEPLOY_WAIT` seconds, 60 by
   default, for a database that starts at the same time).
2. Apache in the foreground, whatever the deploy step said: a database that is not ready does not keep the site down.
## <a name="host"></a>What the container needs from the host

+ **Its settings as a file** at `/var/www/html/.env` (G67): Caligrafy reads `.env`, and its values replace plain
  environment variables of the same name. Coolify mounts it as a *file storage*, `docker run` with
  `-v .env.production:/var/www/html/.env:ro`, and Caligrafy Cloud writes it. Hosts that only offer environment
  variables (Railway, Render, DigitalOcean App Platform) are not supported yet.
+ **The production settings** in that file: `APP_ROOT=` (empty), `APP_ENV=production`, `APP_DEBUG=false`,
  `APP_PROTOCOL=https`, its own `APP_KEY` and `API_KEY` (`php caligrafer.php generatekeys`), `DB_ACTIVATE=true` and the
  production `DB_*`, and the keys of your services. The list and the reasons:
  [Security: the production settings](https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading).
+ **A MySQL database** it can reach.
+ **Two volumes** (G70): `/var/lib/php/sessions` (people stay signed in across deploys) and
  `/var/www/html/public/uploads` (uploads survive a deploy).
+ **HTTPS in front of it**: a load balancer, Coolify's proxy, Caddy... The session cookie is `Secure` behind a proxy
  that sends `X-Forwarded-Proto: https`.
## Common mistakes

+ **The build fails on Composer** (G69): `composer.lock` is missing or older than `composer.json`. Run
  `composer update` and commit it.
+ **A Vite app is blank online**: its `dist/` is not committed. Run `npm run build` in `public/<name>` and commit
  `dist/`.
+ **Everyone is signed out after a deploy, uploads are gone** (G70): no volume at `/var/lib/php/sessions` or
  `/var/www/html/public/uploads`.
+ **Settings given as environment variables are ignored** (G67): give the container its `.env` as a file.
+ **`APP_ROOT=bookshelf` online**: the site's links point to `/bookshelf/...`. `APP_ROOT=` is empty in production.
+ **Pages are slow online**: `APP_DEBUG=true` in the production `.env`.
## Related pages

+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)
+ [The deploy step](https://github.com/caligrafy/caligrafy-quill/wiki/The-Deploy-Step)
+ [Deploying to Caligrafy Cloud](https://github.com/caligrafy/caligrafy-quill/wiki/Deploying-to-Caligrafy-Cloud) · [your own server](https://github.com/caligrafy/caligrafy-quill/wiki/Deploying-to-Your-Own-Server)
+ [Security and upgrading](https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/The-Deploy-Step -->

**The deploy step** is `php caligrafer.php deploy`: what a project runs each time it starts in production, before
Apache serves it. The [production image](https://github.com/caligrafy/caligrafy-quill/wiki/The-Production-Image) runs it
for you. It compiles the settings and brings the database up to date: the framework tables, your `create_db.sql`
scripts when they are new or changed, then your migrations. Since 2.4.0 (migrations 2.18.0, `.env.php` 2.19.0).
## With Claude

```text
/caligrafy-quill:deploy
```

Before a deploy, the skill checks what the deploy step will run: every `create_db.sql` safe to run twice, the
migrations in order, the schedule file valid. After one, `/caligrafy-quill:ship` reads the start-up log.

**Check** before you say OK: the log of the start has only `OK` and `SKIP` lines, and no `FAIL`.
## By hand

On a server without Docker (files copied to PHP and Apache), run it yourself after each copy:

```bash
php caligrafer.php deploy
php caligrafer.php deploy --wait 120      # wait up to 2 minutes for the database
```

On your computer, run it against a production-like settings file to see what it would do:

```bash
docker compose exec dev-box php caligrafer.php deploy --env .env.staging
```

```text
 Caligrafy deploy
 caligrafy-schedule {"version":1,"jobs":[]}
  OK    Settings: .env compiled to .env.php (read without parsing on every request)
  OK    Framework tables: tokens, audit log, job runs, jobs, cache, migrations, scripts
  OK    application/models/Auth/create_db.sql: up to date
  OK    application/models/Bookshelf/create_db.sql: changed: run again
  OK    Migrations: 1 run: 20261107232335_add_books_isbn.sql
```

> `--env` reads the database settings of that file; the `Settings` line always compiles the project's own `.env`.
## <a name="steps"></a>What it does, in order

From [`Caligrafy\Deployer::run()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#deployer-run):

1. **The scheduled jobs line.** `caligrafy-schedule <json>`: the listing of `schedule list --json`, which Caligrafy
   Cloud reads from the log to run the jobs. A schedule file with problems prints
   `caligrafy-schedule-invalid <the problems>` instead, and its jobs do not run. Without the file the list is empty.
2. **The settings.** `.env` compiled to `.env.php`
   ([`Deployer::cacheEnv()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#deployer-cacheenv), the same
   as `env cache`): pages read the settings without parsing `.env` while `.env` keeps that content. Without `.env`:
   `SKIP  Settings: no .env to compile`.
3. **`DB_ACTIVATE`.** Not `true`: `SKIP  Database: DB_ACTIVATE is not true: nothing to prepare`, and it stops there with
   exit code `0`.
4. **The database.** It tries to connect every 2 seconds until `--wait` seconds have passed (60 by default; the image
   passes `CALIGRAFY_DEPLOY_WAIT`). Never reached:
   `FAIL  Database: not reachable after 60 s: check the DB_* settings`, exit code `1`.
5. **The framework tables.** `framework/settings/platform.sql` (every table `CREATE TABLE IF NOT EXISTS`: tokens, the
   audit log, job runs, notifications, jobs, the cache, migrations, Snap), and `caligrafy_scripts`, which records the
   scripts that ran.
6. **The `create_db.sql` scripts.** Every `application/models/<folder>/create_db.sql`, in folder order:

    | The script | Line | What happens |
    | --- | --- | --- |
    | never ran here | `OK  <path>: run` | it runs, and its SHA-256 is recorded |
    | ran, and has not changed | `OK  <path>: up to date` | nothing |
    | changed since it ran | `OK  <path>: changed: run again` | it runs again, and the new SHA-256 is recorded |
    | changed, and drops, deletes or truncates | `WARN  <path>: changed, but it drops or deletes data: not run (php caligrafer.php sql <path> runs it)` | nothing: run it by hand when you mean it |

    "Drops or deletes" is `DROP TABLE`, `DROP DATABASE`, `DROP SCHEMA`, `DROP VIEW`, `DROP COLUMN`, `DELETE FROM` or
    `TRUNCATE`, comments left aside ([`Deployer::destructive()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#deployer-destructive)).
    A statement that fails only because what it adds is already there (a duplicate column, key name or foreign key:
    MySQL errors 1060, 1061, 1826) is skipped, so a script keeps its `ALTER TABLE ... ADD` lines and runs again.
    Other files (`seed.sql`...) are never run.
7. **The migrations.** When `application/migrations` has files, the ones that never ran, in order:
   `OK  Migrations: 1 run: <file>`, or `OK  Migrations: up to date`. A migration edited after it ran:
   `WARN  Migrations: <file>: changed after it ran, not run again (write a new migration for the change)`.

Any SQL error in steps 5 to 7 prints `FAIL  Database: <the error>` (a migration names its file and statement) and the
exit code is `1`. The image starts Apache anyway, after `caligrafer deploy: the database is not prepared (see above)`.
## <a name="scripts"></a>Writing scripts it can run again

Because a changed script runs again on the next start, each `create_db.sql` must be safe to run twice:

```sql
CREATE TABLE IF NOT EXISTS `books` (
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `title` VARCHAR(255) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;

-- added later: skipped once the column is there
ALTER TABLE `books` ADD COLUMN `isbn` VARCHAR(20) NULL;
```

For a change to a table that holds data, prefer a [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations):
it runs once, in order, and says so.
## Common mistakes

+ **A script that drops its table first** (G68): it ran once; changed, it is never run again (`WARN`), and run by hand it
  deletes the data. Use `CREATE TABLE IF NOT EXISTS` and added statements.
+ **`caligrafer deploy: the database is not prepared`**: the line above it says why: the database is not reachable (the
  `DB_*` settings, or a longer `--wait`), or a SQL error that names the statement.
+ **`Host ... is not allowed to connect`** (G71): the database was created but its user was not, often a MySQL killed for
  lack of memory while it initialized. Give it more memory, and recreate its volume while it holds no data.
+ **A setting changed on your own server is ignored**: `.env.php` was compiled from the old `.env`, and is used only
  while `.env` has that content; an edited `.env` is read again. Restart the container, or run `env cache`.
+ **Scheduled jobs do not run on Cloud**: the log has `caligrafy-schedule-invalid`: run `php caligrafer.php schedule list`
  to see the problems.
## Related pages

+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)
+ [The production image](https://github.com/caligrafy/caligrafy-quill/wiki/The-Production-Image)
+ [Migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations) · [Scheduled jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs)
+ [Caligrafer: deploy commands](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer-Deploy-Commands)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Updating-Caligrafy -->

**Updating** moves a project to a newer release of Caligrafy Quill in one command, `php caligrafer.php update`: the
framework, the release's other files, the settings and packages it adds, then the untouched files of `application/`
(`upgrade --apply`). Your code is never overwritten: a file you changed is kept, with the release's version next to it to
merge. This page is the how-to, then what each command does. `update` since 2.9.0; `upgrade` looks for a newer
release since 2.10.0.
## With Claude

```text
/caligrafy-quill:update
```

The `update` skill runs `update --check`, shows what changes, runs `update`, merges every `.caligrafy-new` file into
yours, runs `platform install`, `doctor` and the tests, reads the release notes of every version passed, and refreshes
Claude Code's copy of the plugin.

**Check** before you say OK:
+ `php caligrafer.php version` is the new version;
+ `find . -name '*.caligrafy-new' -not -path './vendor/*' -not -path './backups/*'` prints nothing;
+ `php caligrafer.php doctor` has no `FAIL`, and sign-in and the forms work from a private window.
## By hand

The commands run in the project's Docker server; without Docker, drop `docker compose exec dev-box`.

**1. Start from a clean state.** `git status --short`: commit what is there, so that the update is one change you can
review. With uncommitted changes `update` stops (`--yes` goes on anyway).

**2. See what changes.**

```bash
docker compose exec dev-box php caligrafer.php update --check
```

```text
 Updating Caligrafy Quill 2.24.1 to 2.25.0 (check: nothing is changed)

  replaced    framework/ (will be replaced)
  replaced    claude-plugin/ (will be replaced)
  replaced    caligrafer.php (will be replaced)
  customized  Dockerfile: kept, the new version will be written in Dockerfile.caligrafy-new
  setting     .env: <NEW_SETTING> will be added with its default

 Nothing was changed. php caligrafer.php update applies it.
```

(an example: the files and settings listed are those your two releases differ by). Already on the latest:
` Caligrafy Quill 2.25.0 is the latest: nothing to update. php caligrafer.php upgrade checks application/.`

**3. Update.**

```bash
docker compose exec dev-box php caligrafer.php update            # the latest release
docker compose exec dev-box php caligrafer.php update 2.25.0     # or one release
```

Run it whole, not through `| tail` (G89): it exits with `1` when something did not finish, and its last lines run
`upgrade --apply`. It ends with
` Caligrafy Quill 2.25.0 is in place. ... Check the project with php caligrafer.php doctor; the release notes: https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.25.0`.

**4. Merge every `.caligrafy-new`.**

```bash
find . -name '*.caligrafy-new' -not -path './vendor/*' -not -path './backups/*'
```

For each one, `diff <file> <file>.caligrafy-new`, write your changes plus the release's into `<file>`, then delete the
`.caligrafy-new`.

**5. Check.**

```bash
docker compose exec dev-box php caligrafer.php version
docker compose exec dev-box php caligrafer.php platform install   # the framework tables of the new release
docker compose exec dev-box php caligrafer.php upgrade --local    # nothing outdated left in application/
docker compose exec dev-box php caligrafer.php doctor
docker compose exec dev-box php caligrafer.php test
```

Read the release notes of every version you passed
(`https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-<version>`), and the "From X to Y" notes of
[Security and upgrading](https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading#upgrading).

**6. Commit and deploy.** Commit (`Caligrafy Quill <from> to <to>`), push, deploy. Delete `backups/` once you are done:
git ignores it and the production image leaves it out.
## <a name="update"></a>What `update` does

From [`Caligrafy\Updater`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#updater). It downloads, from
GitHub, the project's own release (`Framework::VERSION`) and the target (the latest by default), and compares your
files with your own release, so it can tell what you changed:

1. **`framework/` and `claude-plugin/`** are the framework's: replaced whole, the files the release dropped included.
   `framework/librairies/app/.env` (written by `initialize`) is kept. Framework files you changed by hand are listed at
   the end; your copies are in the backup.
2. **Every other file of the release** (`caligrafer.php`, `.bin/`, `Dockerfile`, `docker-compose.yaml`, `index.php`,
   `public/css`, `public/js`...):

    | Your file | What happens | Report |
    | --- | --- | --- |
    | missing | added | `added` |
    | the same as your release's | replaced | `replaced` |
    | changed by you | kept; the new version written next to it as `<file>.caligrafy-new` | `customized` |

   Your documents (`README.md`, `CHANGELOG.md`, `CONTRIBUTING.md`, `CODE_OF_CONDUCT.md`, `ARCHITECTURE.md`,
   `LICENSE`) are replaced only when untouched, left alone without a `.caligrafy-new` when you changed them, and never
   added. Never touched here: `application/`, `tests/`, `qa/`, `public/uploads/`, `composer.lock`, the CI files, and the
   project's plugin source files.
3. **Merged** instead of compared: `composer.json` gets the new packages and versions you did not change (then
   `composer update` for them; `--no-composer` prints the command), `.gitignore` the new lines, `.env` the new settings
   with their defaults (existing values are never changed).
4. **The plugin.** The project's plugin source keeps its own name, and Claude Code's copy of the plugin is registered,
   installed or refreshed when `claude` is on this computer.
5. **`application/`**: `php caligrafer.php upgrade --apply --local`, from the new release.

Everything it replaces is copied first to `backups/caligrafy-update-<from>-to-<to>-<time>/`. It refuses a version lower
than the project's (` This project runs <from>: going back to <to> is not supported (restore a backup instead)`).

**A project before 2.9.0** has no `update`: get the command once (G94), then run it.

```bash
curl -fsSL https://raw.githubusercontent.com/caligrafy/caligrafy-quill/master/framework/core/Updater.php -o framework/core/Updater.php
php -r "require 'framework/core/Updater.php'; exit((new Caligrafy\Updater('.'))->run());"
```
## <a name="upgrade"></a>What `upgrade` does

`application/` was copied from `framework/settings/application` when the project was made, and is yours. `upgrade`
(from [`Caligrafy\Upgrader`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#upgrader)) brings its
untouched files up to date. Without `--local`, `--force` or `--keep`, it first asks GitHub for a newer release (G96):
when there is one, `upgrade` is `update --check` and `upgrade --apply` is `update`.

```bash
php caligrafer.php upgrade                                      # dry run
php caligrafer.php upgrade --local                              # this release's templates only
php caligrafer.php upgrade --apply                              # replace the files you never changed
php caligrafer.php upgrade --force application/views/Auth/login.pug          # replace one file you changed
php caligrafer.php upgrade --apply --keep application/views/default/index.pug   # keep a template copy that is now yours
```

It tells your files from untouched copies with `application/.caligrafy-manifest.json` (written by `initialize`) and the
history of every template version (`framework/settings/template-history.json`). Each template file is:

| State | Means | With `--apply` |
| --- | --- | --- |
| `missing` | not in `application/` | added |
| `identical` | the same as the template | nothing |
| `outdated` | an untouched copy of an older template | replaced, with a backup in `backups/caligrafy-upgrade-<time>/` |
| `customized` | changed by you | kept; the new version written next to it as `.caligrafy-new` |
| `kept` | named with `--keep` (remembered in the manifest) | kept; the new version next to it |
| `held` | not added, with the reason: the user capabilities when the project manages users its own way (G80), `AuthController` or `AdminController` when its routes do not need them | nothing; `--force` adds one |
| `routes` | `application/config/routing/web.php`, your routes | never replaced |

It also reports, without changing them: client apps in `public/` that differ from their template, settings of
`.env.example` missing from `.env` and obsolete ones, and Bootstrap 3 classes left in views and apps.
## Common mistakes

+ **`update | tail`** (G89): the pipe hides a failed `composer update` or `upgrade`. Run it whole.
+ **A `.caligrafy-new` left behind**: the release's fixes in that file are not in yours. Merge each one, then delete it.
+ **A new skill is missing in Claude Code after the update** (G103): Claude Code runs its own copy of the plugin. Run
  `php caligrafer.php plugin` on your computer, then restart `claude` in the folder.
+ **`upgrade` on an old project says nothing changes** (G96): before 2.10.0 it compared `application/` with the
  templates of the release the project already ran. Run `update`.
+ **The new framework tables are missing**: an update that adds tables needs `platform install` (the deploy step runs
  it online).
+ **The user capabilities are `held`** (G80): the project manages users its own way; `--force` adds them when you
  want them.
## Related pages

+ [Security and upgrading](https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading)
+ [Caligrafer: maintenance commands](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer-Maintenance-Commands)
+ [Claude Code plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin)
+ [Changelog](https://github.com/caligrafy/caligrafy-quill/blob/master/CHANGELOG.md)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Performance-and-Deployment -->

# Performance and deployment

Since 2.26.0 the production image (`Dockerfile`) is tuned for the container it runs in, and a project can go further
with a response cache and, experimentally, an async server. Every setting below is a line of `.env` (or a variable of
the container's environment); nothing in the application's code changes.

## What the production image does at start

`docker/production/start.sh` runs before Apache:

1. **PHP processes**: `PHP_PROCESSES`. By default it follows the app: **2 per CPU** the container may use (read
   from its cgroup quota, at least 4), or **6 per CPU** (at least 16) when an AI key is set (`OPEN_AI_KEY`,
   `GROQ_API_KEY`, `ANTHROPIC_API_KEY`, `AGENT_API_KEY`, `TOGETHER_API_KEY`, `FIREWORKS_API_KEY`,
   `OPENROUTER_API_KEY`, `WATSON_API_KEY`). Apache's own default (up to 150) makes processes fight over a few CPUs;
   too few, and a page waits behind requests that wait on something else.
2. **Keep-alive off** (`KEEP_ALIVE=on` keeps it). With a fixed number of processes, an idle open connection would hold
   one. The proxy in front (Caligrafy Cloud, Traefik, a load balancer) keeps the visitors' connections open.
3. **The response cache** (`CACHE=off` turns it off) and **OPcache preloading** (`PRELOAD=off`).
4. `php caligrafer.php deploy` (framework tables, SQL scripts, migrations), then `php caligrafer.php optimize` (every
   Pug view compiled, the class map built) as the web server's user: the first visitor of a new container compiles
   nothing.

OPcache keeps the compiled code and stops checking the files for changes (`docker/production/php.ini`): a new version
is a new image.

## How many processes

A process answers one request at a time. A page that only computes is fastest with one process per CPU; a request
that waits (the database, an AI service, an outside API) holds its process while it waits.

| Your app | `PHP_PROCESSES` |
|---|---|
| Pages and the database | leave it empty: 2 per CPU, at least 4 (database waits last milliseconds) |
| Calls an AI service (an AI key is set) | leave it empty: 6 per CPU, at least 16; more if more AI requests can wait at the same time (about 3 MB each when idle) |
| Calls another slow service (a payment API, an SMTP server) from its pages | set it: more than the requests that can wait at the same time |

Measured on 2 CPUs (HTML pages per second while other visitors wait 1 s on an outside call): 4 processes answer
8,051 pages a second when nothing waits, but 32 when 4 visitors wait at once; 8 processes answer 4,180, then 7,550
with 4 waiting, then 14 with 16 waiting. The async server answers AI calls without holding a page's process.

`php caligrafer.php doctor` warns when an app that has AI keys runs fewer than 16 processes, and when the database
allows fewer connections than the processes keep open.

## Persistent database connections

`DB_PERSISTENT` (empty means on, for MySQL and PostgreSQL in a web server): each process keeps its database
connection between requests instead of opening one per request. Before it is reused, a transaction the last request
left open is rolled back and the session time zone is set again. The command line (tests, migrations, the queue)
never keeps one. Each process holds one connection: the database must allow `PHP_PROCESSES` connections plus the
command line and the queue (`doctor` checks it). `DB_PERSISTENT=false` connects on every request.

## The response cache

A capability or a page whose answer is the same for every visitor can say how long that answer may be shared:

```php
#[Capability(name: 'list_books', description: 'The catalog', readOnly: true, public: true, cache: 30)]
class ListBooks extends Service { /* ... */ }
```

```php
Route::page('/about', 'Site/about', ['cache' => 300]);
Route::capabilities('/capabilities');   // GET /capabilities/list_books (a read-only capability may be called with GET)
```

A GET or HEAD from a visitor with no session cookie and no token gets `Cache-Control: public, max-age=30`, and the
production image's Apache keeps the answer in memory: the next visitors get it without PHP. Never kept:

- an answer to a signed-in person or to a token (it is not marked);
- an answer that sets a cookie, such as a page with a form (its CSRF token starts a session): `HttpCache::guard()`
  turns it into `Cache-Control: private, no-store` just before the headers go out;
- any answer other than a 200.

`cache` needs `readOnly: true` and `public: true`. Choose a few seconds for data that changes: a cached answer is not
cleared when the data changes, it expires.

## The async server (experimental)

```bash
php caligrafer.php add async        # Workerman
php caligrafer.php async check      # which capabilities may run there, and why the others may not
```

With `ASYNC=on`, the production image listens with the async server: processes that keep the application in memory
(`ASYNC_WORKERS`, one per CPU by default) answer the capabilities channel (`GET /capabilities`,
`/capabilities/{name}`), and every other request (pages, forms, sign-in, files) goes to Apache unchanged. A request
that brings the session cookie always goes to Apache.

A capability runs there only when its class uses no session, cookie or superglobal (`$_SESSION`, `$_GET`, `$_SERVER`...),
prints nothing, never calls `exit`, keeps no static state, is not `webOnly` and takes no file: `async check` names
what stops each one, and Apache answers the others as before. After each request, what it left in memory is
forgotten (the cache copies, a transaction, container instances). Its callers are tokens and visitors only.

Development: `php caligrafer.php async start --listen http://0.0.0.0:8081` answers on its own port.

## Measured

The numbers of the benchmark (Docker, 2 CPUs and 1 GB for the app) are on the
[benchmark dashboard](https://github.com/caligrafy/caligrafy-quill#performance) and in the release notes of
[2.26.0](Release-notes:-2.26.0).


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Security-Defaults -->

# Security defaults

What Caligrafy Quill does for every project without a line of code (2.26.0), and what one line turns on.

| Protection | How | Since |
|---|---|---|
| CSRF on forms | `Request` checks `_token` on every POST, PUT and DELETE of a form; `=csrf()` in a view; session-authenticated JSON writes need `X-CSRF-Token`; `Route::webhook` is exempt by itself | default |
| SQL injection | the query builder binds every value and checks identifiers | default |
| Mass assignment | only the inputs listed in a capability's `$rules` reach `handle()` | default |
| Passwords | `password_hash` in the shipped sign-up, `password_verify` at sign-in | default |
| Session fixation | `Route::auth` gives a new session id and a new CSRF token at sign-in and sign-out | default |
| Session cookie | `HttpOnly`, and `Secure` on HTTPS (also behind a load balancer that says so) | default |
| Token scopes | a write capability without a `scope` needs a token with the scope named after it, or `*`; read-only and public ones need none; REST, MCP and command-line tokens are all checked, 403 otherwise; `doctor` lists the unscoped writes | **default since 2.26.0** |
| N+1 queries | calling a relation method on one of several rows a query read throws `[ERROR 2004]` in development with the `with()` fix, and logs a warning in production; `->lazy()` or `#[Caligrafy\Lazy]` allow one | **default since 2.26.0** |
| Shared caches | an answer that sets a cookie, goes to a signed-in person or a token, or is not a 200 is never marked public | default (2.26.0) |
| Webhook signatures | `Route::webhook` refuses to register without `verify` (`'stripe'` checks `STRIPE_WEBHOOK_SECRET`) | one line |
| Personal access tokens | shown once, stored as SHA-256, revocable, with an expiry | one command |

Settings that turn a default off, for a migration period only:

- `TOKEN_DEFAULT_SCOPES=false` (deprecated): any token may call a write capability without a scope, as before 2.26.0.
- `STRICT_RELATIONS=false`: the N+1 check warns instead of throwing in development.

`php caligrafer.php doctor` reports both, with the fix.


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin -->

Caligrafy Quill ships with its own **[Claude Code](https://code.claude.com) plugin**, `caligrafy-quill`, in the [`claude-plugin/`](https://github.com/caligrafy/caligrafy-quill/tree/master/claude-plugin) folder of every project. When you open a project in Claude Code, Claude knows the framework from its source: capabilities, the declarative routes, the query builder, models, Pug views, authentication, payments, Vue apps, bots, face detection, machine learning and the AI integrations. It builds the Caligrafy way, **build once, experience everywhere**: a feature becomes a capability, and every experience (pages, Vue apps, REST, AI agents) calls it. With `/caligrafy-quill:idea` it goes from your idea to an app online: **Describe it. Approve it. Ship it.**

Current version: **1.38.0**, for Caligrafy Quill v2.26.0.
## <a name="whatyouget"></a>What the plugin gives Claude

| Component | Name | What it does |
| --- | --- | --- |
| Skill (automatic) | `caligrafy` | The framework knowledge: every page of this wiki, an API reference and 148 verified gotchas (G1-G148) written from the framework source, UI guidelines for every new page, and recipes for AI chat apps and face login. Claude Code loads it whenever it works in a Caligrafy project |
| Command | `/caligrafy-quill:idea` | Your idea turned into a complete app online, with one confirmation: the plan, the project, every feature as a capability, the checks, then GitHub and Caligrafy Cloud |
| Command | `/caligrafy-quill:new-capability` | One capability, served to the channels you need (REST, the JavaScript client, pages and forms, MCP), with a token and tests |
| Command | `/caligrafy-quill:new-resource` | A table, its model, its five CRUD capabilities, their REST routes, pages and forms |
| Command | `/caligrafy-quill:assistant` | Snap Cards and the assistant: every capability as a card, a Home that shows what needs you, a conversation that answers with cards (`Route::snap()`, 2.23.0) |
| Command | `/caligrafy-quill:new-app` | A client app in `public/<name>` (Vue as a library, a Vite SPA, a Watson bot, face detection, machine learning) and its routes |
| Command | `/caligrafy-quill:server` | Starts, stops or checks the Docker development server |
| Command | `/caligrafy-quill:db` | Runs SQL scripts and migrations, lists tables, runs queries |
| Command | `/caligrafy-quill:design` | Restyles every page after a design style (`DESIGN_STYLE`), with one stylesheet |
| Command | `/caligrafy-quill:ship` | Puts the project on GitHub and Caligrafy Cloud by itself |
| Command | `/caligrafy-quill:deploy` | Checks the project is ready for production, then deploys it to Caligrafy Cloud or prepares it for your own server |
| Command | `/caligrafy-quill:marketplace` | Packages an app on Caligrafy Cloud for the marketplace of caligrafy.com and submits it |
| Command | `/caligrafy-quill:update` | Updates the project to the latest release and merges every `.caligrafy-new` file |
| Agent | `caligrafy-reviewer` | Reviews your Caligrafy code for framework bugs and security issues; it never edits files |
| Hook | `php -l` | After Claude writes or edits a `.php` file, checks its syntax and sends an error back to Claude (skipped when PHP is not installed) |

Claude also runs `php caligrafer.php doctor` first when something does not work. The [plugin changelog](https://github.com/caligrafy/caligrafy-quill/blob/master/claude-plugin/README.md#changelog) lists what each version added, and each [release note](https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.19.0) names the plugin version that follows it.
## <a name="install"></a>Installing the plugin

### With a project (recommended)

Every project has a `.claude/settings.json` that registers the plugin's source (a "marketplace": the project folder, through `.claude-plugin/marketplace.json`) and enables the plugin. `initialize` (and so `quickstart`) gives that source the project's own name, `caligrafy-<folder>-<4 letters>`, and `.bin/caligrafer quickstart` registers it with Claude Code when the `claude` command is installed. Open the project and accept the **"trust this folder"** prompt:

```bash
git clone https://github.com/caligrafy/caligrafy-quill.git myapp
cd myapp
.bin/caligrafer quickstart --docker
claude
```

**Check:** type `/caligrafy-quill:` in Claude Code: the commands of the table above are listed. `php caligrafer.php doctor` has a line `Claude Code plugin: caligrafy-quill@caligrafy-<name>`.

### From GitHub, in any folder

In Claude Code:
```text
/plugin marketplace add caligrafy/caligrafy-quill
/plugin install caligrafy-quill@caligrafy
```
or in a terminal:
```bash
claude plugin marketplace add caligrafy/caligrafy-quill
claude plugin install caligrafy-quill@caligrafy
```
The source from GitHub is named `caligrafy` and the plugin `caligrafy-quill`, hence `caligrafy-quill@caligrafy`.

### When a command such as `/caligrafy-quill:design` is unknown

Claude Code keeps one plugin source per name for the whole computer. Projects made before 2.10.1 all named their source `caligrafy`: the first project opened won, the others got its (older) plugin, and none got one once that folder was deleted. In the project, on your computer:
```bash
php caligrafer.php plugin
```
It gives the source the project's own name, registers it (`claude plugin marketplace add`), installs the plugin for the project (`claude plugin install ... --scope project`), and prints `Plugin source: caligrafy-<name>, plugin caligrafy-quill@caligrafy-<name>`. Restart `claude` in the folder. `doctor` warns when a project still shares the name or its plugin is read from another folder.

### When a new skill is missing after an update

Claude Code runs a copy of the plugin made when it was installed, not the project's `claude-plugin/` folder. `php caligrafer.php update` and `php caligrafer.php plugin` refresh that copy when the project's plugin is newer, and `doctor` warns while it is older (`Claude Code runs caligrafy-quill X, this project has Y`). When the update ran in Docker, where `claude` is not installed, run `php caligrafer.php plugin` on your computer in the project folder. Then restart `claude`.
## <a name="commands"></a>Commands

### `/caligrafy-quill:idea <your idea>`
The [Quickstart with Claude](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart-with-Claude). Claude:
1. **Describe it**: turns the idea into a plan (a name, 1 to 3 tables, 4 to 12 capabilities, who may do what, one page per main table, sample data; jobs, alerts and background work only when the idea needs them) and waits for your OK.
2. **Approve it**: sets the project up (`.bin/caligrafer quickstart`, after checking Docker and the ports), writes each table's `create_db.sql` and model, each capability with `php caligrafer.php service`, sign-in with `Route::auth` (a username by default; an email when the plan says so, [kept in the `username` column](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#emailsignin)), the pages with `Route::page` and `Route::form`, the REST routes, the JavaScript client, a card where signed-in people create a token for their AI agents, and tests; then checks every capability (`call`), REST, the page at desktop and phone width, MCP, `test`, `doctor` and a review by `caligrafy-reviewer`, and shows you the app locally.
3. **Ship it**: follows `/caligrafy-quill:ship`.

Your OK at the plan covers everything after it, the framework's `.git` included. You only approve sign-ins in the browser pages Claude opens, and say yes before credits are spent. "Stop before putting it online" makes it wait after the checks.
```text
/caligrafy-quill:idea A reading list: I add books I want to read, mark them as read, and rate them from 1 to 5.
```

### `/caligrafy-quill:new-capability <capability_name> [scope] [read-only|destructive]`
Scaffolds the class with `php caligrafer.php service <Folder>/<Name> --scope <scope>`, writes its description for agents, its `$rules`, `$filters` and `$descriptions`, and a `handle()` that reads with the query builder and refuses with `ServiceError`. It adds the channels you ask for in `web.php`: `Route::capability`, `Route::capabilities` and the JavaScript client, `Route::page`, `Route::form`, `Route::download`, `Route::webhook`, `Route::action` (a web-only capability, for what a page or a form cannot say), `Route::mcp`. It creates a token when an agent needs one, checks every channel (`capabilities`, `call`, REST with and without the scope, MCP `tools/list` and `tools/call`, `audit`), writes a test, and asks `caligrafy-reviewer` to review. Learn more in [Build Once](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP).
```text
/caligrafy-quill:new-capability create_book books:write
```

### `/caligrafy-quill:new-resource <Entity> [field:type ...]`
Capabilities first, every request declared:
+ `application/models/<Entity>/create_db.sql`: the table, `CREATE TABLE IF NOT EXISTS`, an `id` primary key, `<model>_id` foreign keys with unique constraint names;
+ `application/models/<Entity>/<Entity>.php`: the model, one public property per column, its relationships;
+ `list_`, `get_`, `create_`, `update_` and `delete_` capabilities in `application/services/<Entities>/`, the only code that touches the model;
+ their REST routes (`Route::capability`), the pages (`Route::page` with their data from the capabilities) and the forms (`Route::form`) in `web.php`, and the views when you want HTML pages.

Then it offers to run the SQL (`/caligrafy-quill:db`), calls each capability, writes a test and asks for a review. Field types: `string`, `text`, `int`, `decimal`, `bool`, `date`, `datetime`, `json`; `name:fk` is a foreign key to the model `Name`.
```text
/caligrafy-quill:new-resource Book title:string author:string publisher:fk
```

### `/caligrafy-quill:new-app <app | create | bot | facedetect | ml> <name>`
Runs the Caligrafer scaffold into `public/<name>`, adds its page route, prefers capabilities and the JavaScript client for its data, and opens it to check the browser console.
+ `app`: Vue 3 as a library
+ `create`: a Vite Vue single page application (Node.js 20.19+ or 22.12+ on your computer)
+ `bot`: an IBM Watson bot
+ `facedetect`: face detection and recognition (`@vladmandic/face-api` 1.7.15)
+ `ml`: ML Core (ml5 and p5)

The names `app`, `bot`, `__bots__`, `css`, `facedetect`, `fonts`, `images`, `js`, `ml`, `resources` and `uploads` are reserved. The `caligrafy` skill carries two complete recipes Claude follows: **AI chat apps** (OpenAI, Groq, or an open model on OpenRouter or Ollama) and **face login** (face prints checked on the server, with a lockout; a photo can pass, so use it as a convenience or a second factor).
```text
/caligrafy-quill:new-app facedetect faceauth
```

### `/caligrafy-quill:assistant [what the app is about]`
Gives the project [Snap Cards and the assistant](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant) (2.23.0): adds `Route::snap();` to `web.php`, runs `php caligrafer.php snap install`, writes the hints of `application/config/snap.php` from your capabilities (names, columns, the assistant's lines, Home's numbers with their actions, what Home invites to browse, when an action applies), marks slow capabilities `async: true` (a Track card: Task in the background), adds the queue and routines jobs, asks before setting an Anthropic API key (you type it in a hidden prompt), and checks `/assistant` and `/snap`.
```text
/caligrafy-quill:assistant a library app: books, authors and loans
```

### `/caligrafy-quill:server <start | stop | status>`
Checks that Docker runs, that the ports (8080, 8077, 3306) are free, and that `.env` has the Docker settings (`DB_HOST=mysql`, an empty `APP_ROOT`), then starts or stops the server and checks the site answers. When a port is taken it gives the project other ports with a `docker-compose.override.yml`; behind a company proxy that inspects TLS ("self-signed certificate in certificate chain"), it gives the container the company's root certificate. See [Getting Started](https://github.com/caligrafy/caligrafy-quill/wiki/1.-Getting-Started#using-docker).
```text
/caligrafy-quill:server start
```

### `/caligrafy-quill:db <script.sql | tables | query "SQL">`
Runs SQL on the project's MySQL: in the Docker `mysql` container, or a local MySQL with the `DB_*` settings of `.env` (never printing the password).
+ `<script.sql>`: a script such as `application/models/Book/create_db.sql` (the one `new-resource` writes) or `application/models/Bookshelf/create_db.sql`. Scripts with `DROP`, `TRUNCATE` or `DELETE` are shown first and need your OK. A change to a table that holds data becomes a migration (`php caligrafer.php migrate make <name>`, then `migrate`).
+ `tables`: the tables and their row counts.
+ `query "SQL"`: read-only queries; Claude asks before a statement that writes.
```text
/caligrafy-quill:db application/models/Book/create_db.sql
```

### `/caligrafy-quill:design [style | off]`
Reads a whole `DESIGN.md` (84 styles from VoltAgent/awesome-design-md in `framework/design/vendor/`, `interstellar` in `framework/design/local/`, or yours in `application/design/<name>/`), writes one stylesheet, `public/css/designs/<style>.css`, loaded after the Caligrafy stylesheets, sets `DESIGN_STYLE` in `.env`, and checks the sign-in pages and your pages in a browser at desktop and phone width. Caligrafy's files and your views are not edited. `off` brings the Caligrafy look back. Without a style it asks which one. See [Design styles](https://github.com/caligrafy/caligrafy-quill/wiki/Design-Styles).
```text
/caligrafy-quill:design linear.app
```

### `/caligrafy-quill:ship [app-name] [--public]`
Checks the project is ready (no `.env` in git, the scripts safe to run again, the tests), commits, then creates the GitHub repository (private unless `--public`) and pushes it: with your SSH key when GitHub knows it, else over HTTPS with the GitHub CLI, else after installing the GitHub CLI and a code you approve on GitHub's page. It signs in to Caligrafy Cloud with a code you approve on deploy.caligrafy.com (sign up there the first time), creates the app, adds its read-only deploy key to the repository, deploys, and checks the address answers. It never asks for or prints a password, token or key, and asks before spending credits. Run it again after a change: it pushes and deploys again.
```text
/caligrafy-quill:ship myapp
```

### `/caligrafy-quill:deploy [app-name] [--own-server]`
First a read-only check, point by point: Caligrafy Quill 2.4.0 or later, `Dockerfile` and `composer.lock`, no secrets in git, `create_db.sql` scripts safe to run again, no changed migration, the tests, the payment keys, everything committed and pushed. Then it deploys to [Caligrafy Cloud](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online#cloud) with `php caligrafer.php cloud` (`cloud login` approved in your browser), or, with `--own-server`, prepares the project for [Coolify or Docker](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online#ownserver). For a deploy without any hand-off, use `/caligrafy-quill:ship`.
```text
/caligrafy-quill:deploy myapp
```

### `/caligrafy-quill:marketplace [app-name]`
For an app on Caligrafy Cloud that you offered on its page. Claude reads the whole code, runs the app on your computer as a separate Docker project with invented data, and takes screenshots of its key features (5 at most, all different, 1280x800). It writes the title, the description, the prompt that recreates the app with Caligrafy and an estimated price window from a short market study into one private file, `.caligrafy/marketplace.json`, then sends it with `php caligrafer.php cloud submit` and redeploys the app. It often takes 15 to 30 minutes. Caligrafy reviews the listing, sets the final price and publishes it; you earn 25% of every sale. See [the marketplace](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online#marketplace).
```text
/caligrafy-quill:marketplace myapp
```

### `/caligrafy-quill:update [version]`
Asks you to commit uncommitted work first, shows what [`php caligrafer.php update`](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#update) will change, applies it, then merges every `.caligrafy-new` file into your version: your changes kept, the release's added, and a note where both rewrote the same lines. It ends with `version`, `doctor` and `upgrade --local`. A project before 2.9.0 gets the command first.
```text
/caligrafy-quill:update
```
## <a name="reviewer"></a>The `caligrafy-reviewer` agent

It reads the files you name (or your latest changes under `application/`, `tests/`, `public/<app>/` and the SQL scripts), with the framework source and the gotchas as ground truth, and reports findings by severity, each with `file:line`, the failure, the gotcha and a fix. It checks, among others: SQL built from input, CSRF and request header mistakes, route problems, unsafe uploads, outdated templates and libraries, foreign key and pivot schemas, exposed secrets, model code outside capabilities, and since 2.19 a new controller where a declarative route fits, `where` strings the query builder should write, and N+1 loops. It only reads (tools: Read, Grep, Glob, Bash). Ask in plain words:
```text
Review the Books capabilities and web.php with the caligrafy-reviewer agent
```
## <a name="tryit"></a>Try it

A first session in a project set up with the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart):
```text
/caligrafy-quill:server status
/caligrafy-quill:new-resource Author name:string bio:text
/caligrafy-quill:new-resource Book title:string published_year:int summary:text author:fk
/caligrafy-quill:db application/models/Author/create_db.sql
/caligrafy-quill:db application/models/Book/create_db.sql
Turn on sign-in with Route::auth, and let only signed-in people add books
Review the Books capabilities with the caligrafy-reviewer agent
```
`new-resource` writes one folder per entity (`application/models/Book/`, `application/services/Books/`, `application/views/Books/`). The by-hand pages and the [course](https://github.com/caligrafy/caligrafy-quill-course) keep the same Bookshelf in `application/models/Bookshelf/`, `application/services/Bookshelf/` and `application/views/Bookshelf/`: both work, the folders are only for you.

**Check** what Claude wrote before you say OK: the capabilities in `php caligrafer.php capabilities` with the scopes you expect, no `public: true` on a capability that changes data unless you want it, `Route::form` for each form and `Route::action` for what a page or a form cannot say, no new controller, and the page in your browser.
## <a name="knowledge"></a>How the plugin's knowledge is maintained

For contributors to the framework:
+ The numbered files of `skills/caligrafy/reference/` and `wiki-sidebar.md` mirror the pages of this wiki, with a link to the source page at the top of each. Refresh them with `python3 claude-plugin/scripts/sync-wiki.py <wiki clone>`; `--check` exits with `1` when a mirror is stale.
+ `api-reference.md` and `gotchas.md` are written by hand from the framework source. When they and the wiki disagree, the source-verified files win.
+ After a change to `framework/`: update them, run the [QA suite](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Caligrafy#qa), bump `version` in `claude-plugin/.claude-plugin/plugin.json` and the "Current version" line of this page, and follow the [release process](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Caligrafy#release).
+ Load the plugin from a folder with `claude --plugin-dir ./claude-plugin`; validate it with `claude plugin validate ./claude-plugin --strict`.
> **Safety notes**
> + `php caligrafer.php initialize --yes` deletes the `.git` folder (without `--yes` it asks in a terminal and keeps it otherwise). Claude asks before running it in a git repository.
> + Claude never prints or commits the secrets of your `.env`, and approvals for GitHub and Caligrafy Cloud happen in your browser.
## Related pages

+ [Quickstart with Claude](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart-with-Claude)
+ [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer)
+ [Build Once: Services, Capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP)
+ [Testing Caligrafy](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Caligrafy)

<br /><br />
**This is the end of the documentation and the beginning of your journey!**


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# API reference

> Caligrafy Quill 2.26.0: every public class, method and helper function of the framework, generated from the source at each release by `php qa/build-api-reference.php`. Each method shows its signature, its doc comment as written in the code, its parameters, what it returns and the line of the source it is on.

The guides of the wiki explain how to use these classes; start with [How Caligrafy works](https://github.com/caligrafy/caligrafy-quill/wiki/How-Caligrafy-Works).

## [Routing and requests](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing)

Declaring requests and reading them: routes, the request, forms, downloads, webhooks, web-only actions, errors and flash messages.

| Class | Methods | What it is |
|---|---|---|
| [`Caligrafy\Route`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route) | 30 | Class that builds the routing logic of the framework |
| [`Caligrafy\AuthRoutes`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AuthRoutes#authroutes) | 15 | Route::auth() (after Auth::authentication('User', 'users') in web.php) registers, with the views of the authentication module (application/views/Auth/login.pug and register.pug) |
| [`Caligrafy\Request`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#request) | 13 | (no doc comment) |
| [`Caligrafy\Web`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#web) | 7 | A capability declared #[Capability(..., webOnly: true)] and served by Route::action() may return one of these instead of plain data, to choose what the browser gets |
| [`Caligrafy\Action`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#action) | 2 | Route::action('/connect', 'cloud_connect') answers a request with a capability declared webOnly: true, for what a page or a form cannot say: a sign-in between two sites, a session that decides where to go, a gate, a ... |
| [`Caligrafy\Form`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#form) | 11 | Route::form('/books', 'create_book', ['success' =&gt; '/books/{id}', 'flash' =&gt; 'Book added']) answers the form's POST (or its PUT / DELETE through \_method) with a capability, without a controller: 1. the CSRF token of the ... |
| [`Caligrafy\Download`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#download) | 13 | Route::download('/books.csv', 'list_books', ['as' =&gt; 'csv', 'filename' =&gt; 'books.csv']) answers a GET with the result of a read-only capability as an attachment, without a controller: - inputs: the query string and the ... |
| [`Caligrafy\Webhook`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#webhook) | 3 | Route::webhook('/stripe/events', 'record_payment', ['verify' =&gt; 'stripe']) answers the POSTs of another service with a capability, without a controller: - no CSRF token (the sender has no session): the signature of the ... |
| [`Caligrafy\Uploads`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#uploads) | 12 | A capability declares a file input with the rule `file`, an optional allow-list and an optional maximum size |
| [`Caligrafy\Throttle`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#throttle) | 7 | The counts are kept in the Cache (CACHE_STORE: the caligrafy_cache table or a private folder, shared by every session, so that a new cookie does not start again), or in the session when the cache is off. |
| [`Caligrafy\Errors`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#errors) | 6 | The Errors Class is the dictionary of all the error messages in the system |
| [`Caligrafy\Flash`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#flash) | 5 | Route::form() puts the field errors, the old input and a message here before it redirects; the page of the next request reads them with the view helpers errors($field), old($field) and flash($key), then they are gone. |
| [`Caligrafy\Context`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#context) | 13 | Built by the channel adapters (web pages, REST, MCP, CLI) and read by the services: a service never looks at the request, the session or the headers itself. |

## [Controllers and views](https://github.com/caligrafy/caligrafy-quill/wiki/API-Pages)

Rendering pages: the controller base class, the page controller of Route::page, views and design styles.

| Class | Methods | What it is |
|---|---|---|
| [`Caligrafy\Controller`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Controller#controller) | 17 | Parent Class that defines the properties and methods of a controller |
| [`Caligrafy\PageController`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Pages#pagecontroller) | 6 | Route::page('/books/{id}', 'Books/show', ['data' =&gt; ['book' =&gt; 'get_book']]) renders a view through this controller: 1. access: 'signedIn' =&gt; true sends visitors to /login; 'level' =&gt; N also sends people below level N to |
| [`Caligrafy\View`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Pages#view) | 5 | Class View is the view renderer of the application |
| [`Caligrafy\Designs`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Pages#designs) | 12 | A style is a DESIGN.md and the override stylesheet written from it, public/css/designs/&lt;name&gt;.css. |
| [`Caligrafy\HttpCache`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Pages#httpcache) | 4 | A capability declared with cache (#[Capability(..., readOnly: true, public: true, cache: 30)]) answered over REST, or a page declared with Route::page(..., ['cache' =&gt; 30]), is sent with Cache-Control: public, ... |

## [Services and capabilities](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities)

Build once: services, the capability registry, errors, the container, personal access tokens and the audit log.

| Class | Methods | What it is |
|---|---|---|
| [`Caligrafy\Service`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#service) | 4 | Extend it in application/services/, declare the inputs and implement handle() |
| [`Caligrafy\Capability`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capability) | 1 | #[Capability(name: 'create_book', description: 'Adds a book to the catalog', scope: 'books:write')] on a class that extends Caligrafy\Service. |
| [`Caligrafy\Capabilities`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capabilities) | 12 | A capability is a class of application/services/ that extends Service and carries #[Capability(...)]. |
| [`Caligrafy\ServiceError`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#serviceerror) | 8 | A service throws it to refuse a call. |
| [`Caligrafy\Container`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#container) | 10 | Capabilities are made by the container, so a service asks for what it uses in its constructor |
| [`Caligrafy\Tokens`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#tokens) | 11 | A token is `cq_<id>_<secret>`: shown once when it is created, stored only as a SHA-256 hash in caligrafy_tokens with a name, an optional owner (users.id), its scopes, an optional expiry, the last use and a revocation ... |
| [`Caligrafy\Audit`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#audit) | 2 | One row per capability call that changes data, and per refused call: when, who (a user, a token, the CLI), through which channel, which capability and the outcome. |

## [Data](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data)

Models, the query builder, the database connection, migrations, validation and the cache.

| Class | Methods | What it is |
|---|---|---|
| [`Caligrafy\Model`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Model#model) | 24 | Class Model is the base model from which the application models can be extended |
| [`Caligrafy\Query`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query) | 47 | Builds one SQL statement with bound values only. |
| [`Caligrafy\Database`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Database#database) | 16 | The Database class handles all database connections and global functions that interface directly with the database |
| [`Caligrafy\Migrations`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data#migrations) | 7 | application/migrations/&lt;number&gt;_&lt;name&gt;.sql: php caligrafer.php migrate runs, in number order, the files that never ran on this database, and records each one in caligrafy_migrations (its name, its sha256, when). |
| [`Caligrafy\Validator`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data#validator) | 8 | Class that validates inputs |
| [`Caligrafy\Cache`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data#cache) | 9 | CACHE_STORE in .env: database (the default with DB_ACTIVATE=true: the caligrafy_cache table, which the deploy step and php caligrafer.php platform install create, shared by the web server, the queue, scheduled jobs and ... |
| [`Caligrafy\Lazy`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data#lazy) | 0 | #[Caligrafy\Lazy] on a relation method of a model (2.26.0): it may load lazily, without [ERROR 2004] or a warning |
| [`Caligrafy\LazyLoadingException`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data#lazyloadingexception) | 0 | Thrown in development when a relation loads lazily on one of several models a query read ([ERROR 2004], 2.26.0) |

## [Sign-in](https://github.com/caligrafy/caligrafy-quill/wiki/API-Auth)

Users and sessions, passkeys and face login.

| Class | Methods | What it is |
|---|---|---|
| [`Caligrafy\Auth`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Auth#auth) | 13 | Class that defines the properties and methods of an authentication mechanism for UI and API |
| [`Caligrafy\Passkey`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Auth#passkey) | 12 | Passkey wraps lbuchs/webauthn (MIT, no dependencies besides ext-openssl). |
| [`Caligrafy\PasskeyException`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Auth#passkeyexception) | 0 | (no doc comment) |
| [`Caligrafy\FaceLogin`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Auth#facelogin) | 9 | Face login checks used with FaceDetector.liveness() (public/js/services/detect.js) |
| [`Caligrafy\FaceLoginException`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Auth#faceloginexception) | 0 | (no doc comment) |

## [Jobs, notifications and mail](https://github.com/caligrafy/caligrafy-quill/wiki/API-Jobs)

Scheduled jobs, background jobs, web push and email notifications, mail.

| Class | Methods | What it is |
|---|---|---|
| [`Caligrafy\Scheduler`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Jobs#scheduler) | 13 | An app declares its jobs in application/config/schedule.php: each one calls one capability with fixed inputs on a fixed rhythm (every: 1m...1d, or a five-field cron in a timezone). |
| [`Caligrafy\Queue`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Jobs#queue) | 6 | A job is a capability and its input, kept in the caligrafy_jobs table (php caligrafer.php platform install, or the deploy step, creates it). |
| [`Caligrafy\Notify`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Notify#notify) | 20 | Notify::user($userId, ['title' =&gt; ..., 'body' =&gt; ..., 'url' =&gt; ..., 'tag' =&gt; ..., 'urgency' =&gt; ...]) sends to every channel the user turned on and logs the result (caligrafy_notifications: never the body; kept 30 days): ... |
| [`Caligrafy\Mail`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Jobs#mail) | 2 | The Mail class handles all emails sent from the framework |

## [Payments](https://github.com/caligrafy/caligrafy-quill/wiki/API-Payments)

Stripe and cryptocurrency payments.

| Class | Methods | What it is |
|---|---|---|
| [`Caligrafy\Payment`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Payments#payment) | 12 | The Payment handles all payment transactions |
| [`Caligrafy\CryptoPayment`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Payments#cryptopayment) | 9 | CryptoPayment accepts crypto payments (USDC) through the Coinbase Business Checkouts API. |

## [AI](https://github.com/caligrafy/caligrafy-quill/wiki/API-AI)

OpenAI, open models through OpenAI-compatible providers, the OpenAI Assistants and Watson.

| Class | Methods | What it is |
|---|---|---|
| [`Caligrafy\OpenAI`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AI#openai) | 5 | The OpenAI class handles all exchanges with the OpenAI models (text and images) |
| [`Caligrafy\Agent`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AI#agent) | 13 | The Agent class talks to open models through OpenAI-compatible providers: Groq (default, through groq-php), Together AI, Fireworks AI, OpenRouter, a local Ollama or any custom endpoint. |
| [`Caligrafy\Assistant`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AI#assistant) | 12 | The Assistant class runs conversations with OpenAI models through the Responses and Conversations APIs. |
| [`Caligrafy\Watson`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AI#watson) | 11 | The Watson class handles all exchanges with the Watson Assistant |

## [Interfaces: REST, the JS client and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces)

The channels that serve the capabilities besides web pages.

| Class | Methods | What it is |
|---|---|---|
| [`Caligrafy\Rest`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#rest) | 4 | Answers HTTP requests with capabilities, in JSON: - Route::capability('POST', '/books', 'create_book') maps one route to one capability - Route::capabilities('/capabilities') adds GET /capabilities (what the caller may ... |
| [`Caligrafy\Client`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#client) | 2 | One ES module, no dependency, for the Vue apps, the Vite SPA and Node scripts: one async function per capability (create_book becomes createBook) plus call(name, input) and capabilities(). |
| [`Caligrafy\Mcp\Http`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#mcp-http) | 3 | One JSON-RPC message per POST, answered with application/json (no event stream: every tool answers at once). |
| [`Caligrafy\Mcp\Server`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#mcp-server) | 6 | JSON-RPC 2.0 messages of MCP, independent of the transport (Http for Streamable HTTP, caligrafer mcp for stdio): initialize, ping, tools/list, tools/call; notifications get no answer. |
| [`Caligrafy\Async\Kernel`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#async-kernel) | 5 | What the async server runs, whatever server it is: boot() once per process (settings, constants, the class map, the application's config and container, the capabilities), then handle() for each request, one at a time ... |
| [`Caligrafy\Async\Eligibility`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#async-eligibility) | 3 | The async server keeps the application in memory and answers many requests from one process, so a capability it runs must not keep anything from one caller to the next, nor talk to the web server's request directly. |
| [`Caligrafy\Async\WorkermanServer`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#async-workermanserver) | 1 | Workerman (pure PHP, composer require workerman/workerman: php caligrafer.php add async) keeps a few processes that each hold the application in memory (Kernel::boot) and many open connections, answering one request at ... |

## [Snap](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap)

Snap Cards and the assistant (namespace Caligrafy\Snap): cards built from what capabilities declare, the conversation, the planner and the setup.

| Class | Methods | What it is |
|---|---|---|
| [`Caligrafy\Snap\Cards`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Cards#snap-cards) | 16 | Snap Cards (2.23.0): every card is built from what a capability already declares |
| [`Caligrafy\Snap\Hints`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-hints) | 3 | Snap Cards work without any hint: every card is built from what a capability declares (its rules, descriptions, readOnly and destructive). |
| [`Caligrafy\Snap\Views`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-views) | 7 | How a Show card looks, best first (2.25.0): 1. its card view: application/views/snap/&lt;capability&gt;.pug, a Pug view made for the card, in the app's own markup and |
| [`Caligrafy\Snap\Designer`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-designer) | 5 | A capability shown through its own page uses that page (Snap\Views). |
| [`Caligrafy\Snap\Conversation`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Conversation#snap-conversation) | 15 | The Snap shell's two spaces (2.23.0) |
| [`Caligrafy\Snap\Planner`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-planner) | 4 | The Snap shell's planner (2.23.0): Claude reads what the person typed or said and answers with cards. |
| [`Caligrafy\Snap\Flow`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-flow) | 2 | The next card for a capability and its inputs, the same whoever asks (a card that is sent, the shell's fast path, the model's choice): one place decides, so the planner can never take a shortcut around consent. |
| [`Caligrafy\Snap\Input`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-input) | 1 | The inputs of a card arrive as an object, or its JSON (agents and addresses send JSON text): this gives the plain values only (a nested object or list is left out: a card's inputs are scalars). |
| [`Caligrafy\Snap\Reads`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-reads) | 2 | The reads of one request, once (2.23.0): Home asks the same lists for its alerts, insights and picks; each runs once per person per request. |
| [`Caligrafy\Snap\Say`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-say) | 2 | The assistant's line after every action (2.23.0): whatever the person did (sent a form, picked a choice, confirmed, opened a row, undid, saved a shortcut), the answer carries what the assistant says about it, shown in ... |
| [`Caligrafy\Snap\Consent`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-consent) | 3 | Snap consent (2.23.0): nothing that changes data runs from a card until the person confirms it. |
| [`Caligrafy\Snap\Offers`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-offers) | 13 | Offer: Suggestion and Offer: Routine (2.23.0): the assistant notices what a person does again and again, only if they turned noticing on, and offers to help. |
| [`Caligrafy\Snap\Shortcuts`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-shortcuts) | 5 | Go: Shortcut cards (2.23.0): a request a person saved (a capability with its inputs), run with one click. |
| [`Caligrafy\Snap\Tasks`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-tasks) | 5 | Track: Task cards (2.23.0): work that runs in the background for one person. |
| [`Caligrafy\Snap\Discover`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-discover) | 2 | Discover (2.23.0): Home surfaces the things this application is about, to invite browsing, the way a shop surfaces products. |
| [`Caligrafy\Snap\Setup`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-setup) | 2 | install: the tables (framework/settings/platform.sql), a starter application/config/snap.php when there is none, then the two lines to add by hand (they are the app's own files): Route::snap(); in web.php, and the ... |
| [`Caligrafy\Snap\Shell`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-shell) | 5 | The Snap shell's fast path (2.23.0): what it can answer without a model, at once and for free |

## [Testing](https://github.com/caligrafy/caligrafy-quill/wiki/API-Testing)

The base class of the tests of an application (tests/, php caligrafer.php test).

| Class | Methods | What it is |
|---|---|---|
| [`Caligrafy\Testing\TestCase`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Testing#testing-testcase) | 9 | Test what the app does through its capabilities, as the pages, REST, the JS client and agents reach them |

## [Framework and tooling](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling)

The framework bootstrap and what the caligrafer command runs: the CLI, doctor, update, upgrade, deploy, Cloud, quickstart and the plugin copy.

| Class | Methods | What it is |
|---|---|---|
| [`Caligrafy\Features`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#features) | 14 | The SDKs that only some applications use are no longer in Caligrafy's composer.json (they are suggested): a project adds the one it needs with php caligrafer.php add &lt;feature&gt;, which runs composer require with the ... |
| [`Caligrafy\FeatureMissing`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#featuremissing) | 0 | A feature whose SDK (or files) this project does not install: the message names the command that adds it |
| [`Caligrafy\Framework`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#framework) | 3 | Class Framework that loads the entire framework Framework loader |
| [`Caligrafy\Loader`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#loader) | 2 | Class Loader loads any additional librairies and helpers needed per module Framework loader loads any additional librairies and helpers needed per module |
| [`Caligrafy\ClassMap`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#classmap) | 10 | Before 2.18.0 the first unknown class of a request loaded every PHP file of framework/core, framework/database, framework/interfaces, application/ and tests/. |
| [`Caligrafy\Caligrafer`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#caligrafer) | 4 | Class Caligrafer: the framework as the command line starts it (php caligrafer.php): settings, constants and the class map, without routes or a session cookie |
| [`Caligrafy\Doctor`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#doctor) | 6 | Every check is read-only: it lists, reads or connects, it never creates, charges or sends anything (the only exception is Watson when its assistants cannot be listed: a session is opened and closed right away). |
| [`Caligrafy\Updater`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#updater) | 4 | php caligrafer.php update [&lt;version&gt;] downloads the project's release (Framework::VERSION) and the target release (the latest by default), then: 1. framework/ and claude-plugin/ are the framework's: replaced whole ... |
| [`Caligrafy\Upgrader`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#upgrader) | 5 | Compares application/ with framework/settings/application and reports or applies the template updates. |
| [`Caligrafy\Deployer`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#deployer) | 7 | 1. waits for the database (a new server starts its database at the same time as the app) 2. creates the framework tables (framework/settings/platform.sql, safe to run again) 3. runs every ... |
| [`Caligrafy\CloudClient`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#cloudclient) | 3 | Calls the capabilities of Caligrafy Cloud (POST &lt;url&gt;/capabilities/&lt;name&gt;) with a personal access token of the account. |
| [`Caligrafy\Quickstart`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#quickstart) | 10 | Every step can be run again: it only does what is missing. |
| [`Caligrafy\PluginSource`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#pluginsource) | 7 | A project enables the Claude Code plugin of its own claude-plugin/ folder through .claude/settings.json: a plugin source (a "marketplace", declared in .claude-plugin/marketplace.json) at "./", and the plugin ... |

## [Helper functions](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers)

65 global functions of `framework/helpers`: [`generateKey()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-generatekey), [`generateToken()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-generatetoken), [`encryptDecrypt()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-encryptdecrypt), [`isSessionExpired()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-issessionexpired), [`saveInSession()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-saveinsession), [`clearFromSession()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-clearfromsession), [`scripts()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-scripts), [`design_stylesheet()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-design-stylesheet), [`copyright()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-copyright), [`keywords()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-keywords), [`metadata()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-metadata), [`session()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-session), [`caligrafySessionNeeded()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-caligrafysessionneeded), [`caligrafySessionReady()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-caligrafysessionready), [`caligrafySessionMustSave()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-caligrafysessionmustsave), [`caligrafySessionStart()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-caligrafysessionstart), [`caligrafySessionSnapshot()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-caligrafysessionsnapshot), [`caligrafySessionShutdown()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-caligrafysessionshutdown), [`view()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-view), [`api()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-api), [`findKey()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-findkey), [`recursive_filter()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-recursive-filter), [`loadConstantFromArray()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-loadconstantfromarray), [`terminateSession()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-terminatesession), [`getGlobalInformation()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-getglobalinformation), [`isAllowedUpload()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-isallowedupload), [`uploadFile()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-uploadfile), [`deleteFile()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-deletefile), [`isJson()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-isjson), [`sanitize()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-sanitize), [`request()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-request), [`connect()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-connect), [`import()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-import), [`parsePath()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-parsepath), [`currentRoute()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-currentroute), [`currentBind()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-currentbind), [`startWith()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-startwith), [`endWith()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-endwith), [`sanitizePath()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-sanitizepath), [`associate()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-associate), [`bindRouteToVar()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-bindroutetovar), [`parseRoute()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-parseroute), [`_require_all()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-require-all), [`singularize()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-singularize), [`methodField()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-methodfield), [`csrf()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-csrf), [`errors()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-errors), [`old()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-old), [`flash()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-flash), [`authorize()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-authorize), [`authorized()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-authorized), [`unauthorize()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-unauthorize), [`user()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-user), [`guard()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-guard), [`logout()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-logout), [`imageCanva()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-imagecanva), [`load_script()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-load-script), [`redirect()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-redirect), [`getRelativeTime()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-getrelativetime), [`rearrange()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-rearrange), [`httpFile()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-httpfile), [`httpRequest()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-httprequest), [`now()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-now), [`sendMail()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-sendmail), [`arraySort()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers#fn-arraysort).

---

86 classes, 677 public methods, 65 functions.


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Routing and requests

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Declaring requests and reading them: routes, the request, forms, downloads, webhooks, web-only actions, errors and flash messages.

| Class | What it is |
|---|---|
| [`Caligrafy\Route`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route#route) | Class that builds the routing logic of the framework |
| [`Caligrafy\AuthRoutes`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AuthRoutes#authroutes) | Route::auth() (after Auth::authentication('User', 'users') in web.php) registers, with the views of the authentication module (application/views/Auth/login.pug and register.pug) |
| [`Caligrafy\Request`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#request) | (no doc comment) |
| [`Caligrafy\Web`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#web) | A capability declared #[Capability(..., webOnly: true)] and served by Route::action() may return one of these instead of plain data, to choose what the browser gets |
| [`Caligrafy\Action`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#action) | Route::action('/connect', 'cloud_connect') answers a request with a capability declared webOnly: true, for what a page or a form cannot say: a sign-in between two sites, a session that decides where to go, a gate, a ... |
| [`Caligrafy\Form`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#form) | Route::form('/books', 'create_book', ['success' =&gt; '/books/{id}', 'flash' =&gt; 'Book added']) answers the form's POST (or its PUT / DELETE through \_method) with a capability, without a controller: 1. the CSRF token of the ... |
| [`Caligrafy\Download`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#download) | Route::download('/books.csv', 'list_books', ['as' =&gt; 'csv', 'filename' =&gt; 'books.csv']) answers a GET with the result of a read-only capability as an attachment, without a controller: - inputs: the query string and the ... |
| [`Caligrafy\Webhook`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#webhook) | Route::webhook('/stripe/events', 'record_payment', ['verify' =&gt; 'stripe']) answers the POSTs of another service with a capability, without a controller: - no CSRF token (the sender has no session): the signature of the ... |
| [`Caligrafy\Uploads`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#uploads) | A capability declares a file input with the rule `file`, an optional allow-list and an optional maximum size |
| [`Caligrafy\Throttle`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#throttle) | The counts are kept in the Cache (CACHE_STORE: the caligrafy_cache table or a private folder, shared by every session, so that a new cookie does not start again), or in the session when the cache is off. |
| [`Caligrafy\Errors`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#errors) | The Errors Class is the dictionary of all the error messages in the system |
| [`Caligrafy\Flash`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#flash) | Route::form() puts the field errors, the old input and a message here before it redirects; the page of the next request reads them with the view helpers errors($field), old($field) and flash($key), then they are gone. |
| [`Caligrafy\Context`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing#context) | Built by the channel adapters (web pages, REST, MCP, CLI) and read by the services: a service never looks at the request, the session or the headers itself. |

<a name="route"></a>
## class Caligrafy\Route

Class that builds the routing logic of the framework

Its 30 public methods have a page of their own: [Caligrafy\Route](https://github.com/caligrafy/caligrafy-quill/wiki/API-Route).

<a name="authroutes"></a>
## class Caligrafy\AuthRoutes

Route::auth() (after Auth::authentication('User', 'users') in web.php) registers, with the views of the authentication module (application/views/Auth/login.pug and register.pug)

Its 15 public methods have a page of their own: [Caligrafy\AuthRoutes](https://github.com/caligrafy/caligrafy-quill/wiki/API-AuthRoutes).

<a name="request"></a>
## class Caligrafy\Request

```php
namespace Caligrafy;

class Request extends \stdClass
```

Source: [framework/core/Request.php:6](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Request.php#L6)

_No doc comment on this class._

### Public properties

+ `public $uriParameters`: array uriParameters defines the uri request parameters
+ `public $method`: array method fetches the http request method
+ `public $uri`: string uri defines the uri of the request without query parameters
+ `public $fullUri`: string fulluri defines the full uri of the request includng the query parameters
+ `public $uriComponents`: array uriComponents defines a list of all the elements of the uri
+ `public $host`: string host reads the host information as taken from the headers of the request
+ `public $authorization`: string host reads the host information as taken from the headers of the request
+ `public $cache`: array cache has all the headers information of the request
+ `public $userAgent`: array userAgent has all the headers information of the request
+ `public $accept`: array accept has all the headers information of the request
+ `public $acceptEncoding`: array acceptEncoding has all the headers information of the request
+ `public $acceptLanguage`: array acceptLanguage has all the headers information of the request
+ `public $cookie`: array cookie has all the headers information of the request
+ `public $parsedURI`: array parsedURI has all the headers information of the request
+ `public $currentRoute`: array currentRoute has all the headers information of the request
+ `public $currentBind`: array currentBind has all the headers information of the request
+ `public $fetch`: array fetch has all the headers information of the request
+ `public $parameters`: array fetches all the request parameters
+ `public $token`: array|null the personal access token of the request, once authorizeApiRequest() or Context::fromRequest() checked it

### Methods

+ [`->__construct()`](#request-construct)
+ [`->authorizeApiRequest()`](#request-authorizeapirequest)
+ [`->authorizeSessionRequest()`](#request-authorizesessionrequest)
+ [`->apiRefusal()`](#request-apirefusal)
+ [`->bearer()`](#request-bearer)
+ [`->isLegacyApiKey()`](#request-islegacyapikey)
+ [`Request::legacyKeysDisabled()`](#request-legacykeysdisabled)
+ [`->wantsJson()`](#request-wantsjson)
+ [`->fetch()`](#request-fetch)
+ [`->forClient()`](#request-forclient)
+ [`->fullUri()`](#request-fulluri)
+ [`->parameters()`](#request-parameters)
+ [`->files()`](#request-files)

<a name="request-construct"></a>
#### `->__construct()`

```php
public function __construct()
```

_No doc comment._

Source: [framework/core/Request.php:129](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Request.php#L129)

<a name="request-authorizeapirequest"></a>
#### `->authorizeApiRequest()`

```php
public function authorizeApiRequest($scope = '*')
```

Checks if API requests are authorized

- a personal access token (Bearer cq_...) that grants $scope; the controller routes of web.php ask for '\*', so they accept the tokens that grant everything, as the legacy key did
- the legacy API key (any key generated for this APP_KEY), unless LEGACY_API_KEY=false

**Parameters**

+ `$scope` `string`, default `'*'`: the scope the route needs

Source: [framework/core/Request.php:162](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Request.php#L162)

<a name="request-authorizesessionrequest"></a>
#### `->authorizeSessionRequest()`

```php
public function authorizeSessionRequest()
```

Whether a JSON call comes from a page of this application: it carries the session's CSRF token in an
X-CSRF-Token header (or \_token), which only pages of this origin can read. The controller then sees the
signed-in user, or a visitor, exactly as for a form post

Source: [framework/core/Request.php:184](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Request.php#L184)

<a name="request-apirefusal"></a>
#### `->apiRefusal()`

```php
public function apiRefusal()
```

Why a JSON call to a controller route was refused, for the [ERROR 1004] message

Source: [framework/core/Request.php:195](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Request.php#L195)

<a name="request-bearer"></a>
#### `->bearer()`

```php
public function bearer()
```

The bearer value of the Authorization header (null when there is none)

Source: [framework/core/Request.php:216](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Request.php#L216)

<a name="request-islegacyapikey"></a>
#### `->isLegacyApiKey()`

```php
public function isLegacyApiKey($key)
```

Whether a value is a legacy API key of this project (encrypts APP_KEY), and legacy keys are allowed

**Parameters**

+ `$key`

Source: [framework/core/Request.php:224](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Request.php#L224)

<a name="request-legacykeysdisabled"></a>
#### `Request::legacyKeysDisabled()`

```php
public static function legacyKeysDisabled()
```

LEGACY_API_KEY=false in .env turns the legacy API key off (tokens only)

Source: [framework/core/Request.php:236](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Request.php#L236)

<a name="request-wantsjson"></a>
#### `->wantsJson()`

```php
public function wantsJson()
```

Checks if request needs a Json as a way to recognize API calls

Source: [framework/core/Request.php:245](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Request.php#L245)

<a name="request-fetch"></a>
#### `->fetch()`

```php
public function fetch($argument)
```

Fetches all the arguments and parameters of a request call

**Parameters**

+ `$argument`: defines the argument looked up

Source: [framework/core/Request.php:264](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Request.php#L264)

<a name="request-forclient"></a>
#### `->forClient()`

```php
public function forClient()
```

What a client app page may see of the request (env.request of the Client/app view, 2.19.1): the address,
the method, the route and its bound values, and the query string. Never the Cookie (the session id) nor the
Authorization header, nor any other header that can carry a credential. A POST body is left out too: only the
query string of the address is given

**Returns** `array`

Source: [framework/core/Request.php:283](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Request.php#L283)

<a name="request-fulluri"></a>
#### `->fullUri()`

```php
public function fullUri()
```

Fetches the full uri a request

Source: [framework/core/Request.php:306](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Request.php#L306)

<a name="request-parameters"></a>
#### `->parameters()`

```php
public function parameters()
```

Fetches the parameters of a request

Source: [framework/core/Request.php:314](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Request.php#L314)

<a name="request-files"></a>
#### `->files()`

```php
public function files($fileAttribute)
```

Fetches the files uploaded with a request

**Parameters**

+ `$fileAttribute`

Source: [framework/core/Request.php:324](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Request.php#L324)

<a name="web"></a>
## class Caligrafy\Web

```php
namespace Caligrafy;

class Web
```

Source: [framework/core/Web.php:22](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Web.php#L22)

Class Web (2.21.0)
A capability declared #[Capability(..., webOnly: true)] and served by Route::action() may return one of these
instead of plain data, to choose what the browser gets:

```
return Web::view('Books/show', ['book' => $book]);
return Web::view('Books/missing', ['message' => 'No such book'], 404);
return Web::redirect('/books');
return Web::redirect('https://checkout.stripe.com/...', 303);
return Web::json(['enrolled' => true], 201);
return Web::text('ok')->header('Cache-Control', 'no-store');
```

### Methods

+ [`Web::view()`](#web-view)
+ [`Web::redirect()`](#web-redirect)
+ [`Web::json()`](#web-json)
+ [`Web::text()`](#web-text)
+ [`->header()`](#web-header)
+ [`->describe()`](#web-describe)
+ [`->send()`](#web-send)

<a name="web-view"></a>
#### `Web::view()`

```php
public static function view($view, array $data = array(), $status = 200)
```

A view, given who is signed in as Route::page gives it ('authorized', 'user'); $data wins

**Parameters**

+ `$view`
+ `$data` `array`, default `array()`
+ `$status`, default `200`

Source: [framework/core/Web.php:39](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Web.php#L39)

<a name="web-redirect"></a>
#### `Web::redirect()`

```php
public static function redirect($to, $status = 302)
```

A path of this site or a full http(s) address

**Parameters**

+ `$to`
+ `$status`, default `302`

Source: [framework/core/Web.php:45](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Web.php#L45)

<a name="web-json"></a>
#### `Web::json()`

```php
public static function json($data, $status = 200)
```

_No doc comment._

**Parameters**

+ `$data`
+ `$status`, default `200`

Source: [framework/core/Web.php:50](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Web.php#L50)

<a name="web-text"></a>
#### `Web::text()`

```php
public static function text($body = '', $status = 200)
```

_No doc comment._

**Parameters**

+ `$body`, default `''`
+ `$status`, default `200`

Source: [framework/core/Web.php:55](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Web.php#L55)

<a name="web-header"></a>
#### `->header()`

```php
public function header($name, $value)
```

One more response header

**Parameters**

+ `$name`
+ `$value`

Source: [framework/core/Web.php:61](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Web.php#L61)

<a name="web-describe"></a>
#### `->describe()`

```php
public function describe()
```

What it answers, for tests: ['type', 'target', 'data', 'status', 'headers']

Source: [framework/core/Web.php:68](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Web.php#L68)

<a name="web-send"></a>
#### `->send()`

```php
public function send()
```

Answers the request

Source: [framework/core/Web.php:74](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Web.php#L74)

<a name="action"></a>
## class Caligrafy\Action

```php
namespace Caligrafy;

class Action
```

Source: [framework/core/Action.php:27](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Action.php#L27)

Class Action (2.21.0)
Route::action('/connect', 'cloud_connect') answers a request with a capability declared webOnly: true, for what a
page or a form cannot say: a sign-in between two sites, a session that decides where to go, a gate, a payment page.
1. access: the 'signedIn', 'level', 'comeBack' and 'visitorsOnly' options of Route::page
2. the capability is called with the query string or the form, and the route variables (which win), as the person who sent it, with its rules, permissions and audit log like any capability
3. its answer goes to the browser: a Caligrafy\Web (a view, a redirect, JSON, text), or JSON of the plain data A JSON call needs the page's X-CSRF-Token or an API token, signed in or not ([ERROR 1004], 401)
4. a refusal it does not answer itself is treated as in Route::form: invalid input or a conflict goes back with errors(), old() and flash('error'); a visitor goes to sign in; forbidden is 403, anything else 404. JSON requests get the REST error.
Unlike every other capability, it may read the session and the request and may sign people in, and a GET may change
data: so a webOnly capability is reachable through Route::action only, never through REST, MCP, the JS client,
Route::page, Route::form or a controller.

### Methods

+ [`Action::handle()`](#action-handle)
+ [`Action::answer()`](#action-answer)

<a name="action-handle"></a>
#### `Action::handle()`

```php
public static function handle($capability, array $options = array(), $request = null)
```

_No doc comment._

**Parameters**

+ `$capability`
+ `$options` `array`, default `array()`
+ `$request`, default `null`

Source: [framework/core/Action.php:29](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Action.php#L29)

<a name="action-answer"></a>
#### `Action::answer()`

```php
public static function answer($answer)
```

Sends what the capability answered

**Parameters**

+ `$answer`

Source: [framework/core/Action.php:64](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Action.php#L64)

<a name="form"></a>
## class Caligrafy\Form

```php
namespace Caligrafy;

class Form
```

Source: [framework/core/Form.php:29](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Form.php#L29)

Class Form (2.19.0)
Route::form('/books', 'create_book', ['success' =&gt; '/books/{id}', 'flash' =&gt; 'Book added']) answers the form's POST
(or its PUT / DELETE through \_method) with a capability, without a controller:
1. the CSRF token of the form is checked by the request, as for every form (error 3000, 403)
2. the capability is called with the form fields, the files of its `file` inputs (Uploads) and the route variables (which win), as the person who sent the form (Context::fromRequest(..., 'web'))
3. success: a redirect to 'success' (a path whose {placeholders} are filled from the result, then from the route variables, or a callable($result) returning the path; without it, back to the form), with the 'flash' message (also with placeholders) for flash('success')
4. invalid input (or a conflict): back to the form ('back', else the Referer of this site, else /) with the field errors, the message and the old input for the next request: errors($field), old($field), flash('error')
5. a visitor where the capability needs someone: to the sign-in page ('signIn', default /login) when Auth is active, else 403; forbidden: 403 (error 1006); not found: 404 (error 1005)
A JSON request (Accept: application/json) gets the REST answer instead of redirects: {"data": ...} with 200 (201 for a
POST that changes data), or {"error": ...} with 401, 403, 404, 409 or 422. Sent with the session cookie, it needs the
X-CSRF-Token header, as REST.

### Constants

+ `SECRET = '/pass|secret|token|card|cvc|cvv|iban/i'`: fields never kept as old input

### Methods

+ [`Form::handle()`](#form-handle)
+ [`Form::environment()`](#form-environment)
+ [`Form::outcome()`](#form-outcome)
+ [`Form::problems()`](#form-problems)
+ [`Form::withServerInputs()`](#form-withserverinputs)
+ [`Form::perform()`](#form-perform)
+ [`Form::fill()`](#form-fill)
+ [`Form::back()`](#form-back)
+ [`Form::sameSite()`](#form-samesite)
+ [`Form::oldInput()`](#form-oldinput)
+ [`Form::refused()`](#form-refused)

<a name="form-handle"></a>
#### `Form::handle()`

```php
public static function handle($capability, array $options = array(), $request = null)
```

Answers the current request (the route's closure)

**Parameters**

+ `$capability`
+ `$options` `array`, default `array()`
+ `$request`, default `null`

Source: [framework/core/Form.php:37](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Form.php#L37)

<a name="form-environment"></a>
#### `Form::environment()`

```php
public static function environment($request)
```

What outcome() and refused() need to know about the request

**Parameters**

+ `$request`

Source: [framework/core/Form.php:47](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Form.php#L47)

<a name="form-outcome"></a>
#### `Form::outcome()`

```php
public static function outcome(
    $capability,
    array $options,
    array $input,
    Context $context,
    $json,
    array $env = array()
)
```

What a form post leads to, without answering it (testable without a server). Flash data is written to the session.

**Parameters**

+ `$capability`
+ `$options` `array`
+ `$input` `array`
+ `$context` `Context`
+ `$json`
+ `$env` `array`, default `array()`: referer, host, route (route variables), bearer (bool), csrf (bool: X-CSRF-Token is the session's), method, uploads (Uploads|null)

**Returns** `array`: ['redirect' =&gt; url] | ['status' =&gt; int, 'json' =&gt; array] | ['error' =&gt; 1005|1006]

Source: [framework/core/Form.php:67](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Form.php#L67)

<a name="form-problems"></a>
#### `Form::problems()`

```php
public static function problems(array $options, array $input)
```

What the 'same' and 'accepted' options refuse (2.20.0): [field =&gt; message]

```
'same' => ['password_again' => ['password', 'The two passwords are not the same']]
'accepted' => ['terms' => 'Accept the terms of use to create an account']
```

**Parameters**

+ `$options` `array`
+ `$input` `array`

Source: [framework/core/Form.php:121](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Form.php#L121)

<a name="form-withserverinputs"></a>
#### `Form::withServerInputs()`

```php
public static function withServerInputs(array $options, array $input, array $route = array())
```

The inputs the server sets itself (2.20.0, 'inputs': an array, or a callable($input) returning one): they replace
what the form sent. The route variables still win. They are not kept for old().

**Parameters**

+ `$options` `array`
+ `$input` `array`
+ `$route` `array`, default `array()`

Source: [framework/core/Form.php:144](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Form.php#L144)

<a name="form-perform"></a>
#### `Form::perform()`

```php
public static function perform(array $outcome)
```

Answers an outcome

**Parameters**

+ `$outcome` `array`

Source: [framework/core/Form.php:174](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Form.php#L174)

<a name="form-fill"></a>
#### `Form::fill()`

```php
public static function fill($template, array $values, $encode = true)
```

Fills {name} placeholders: Form::fill('/books/{id}', ['id' =&gt; 3]) is /books/3

**Parameters**

+ `$template`
+ `$values` `array`
+ `$encode` `bool`, default `true`: url-encode the values (paths)

+ **@throws** \LogicException when a placeholder has no value

Source: [framework/core/Form.php:199](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Form.php#L199)

<a name="form-back"></a>
#### `Form::back()`

```php
public static function back(array $options, array $env)
```

Where "back" is: the 'back' option (with the route variables), else the Referer when it is a page of this site,
else the home page

**Parameters**

+ `$options` `array`
+ `$env` `array`

Source: [framework/core/Form.php:214](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Form.php#L214)

<a name="form-samesite"></a>
#### `Form::sameSite()`

```php
public static function sameSite($url, $host)
```

Whether a URL is a page of this host (host and port): never redirect elsewhere from a Referer

**Parameters**

+ `$url`
+ `$host`

Source: [framework/core/Form.php:229](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Form.php#L229)

<a name="form-oldinput"></a>
#### `Form::oldInput()`

```php
public static function oldInput(array $input)
```

The input kept for old(): no secrets, no files, no framework fields

**Parameters**

+ `$input` `array`

Source: [framework/core/Form.php:242](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Form.php#L242)

<a name="form-refused"></a>
#### `Form::refused()`

```php
public static function refused(ServiceError $e, array $options, array $input, $json, array $env)
```

_No doc comment._

**Parameters**

+ `$e` `ServiceError`
+ `$options` `array`
+ `$input` `array`
+ `$json`
+ `$env` `array`

Source: [framework/core/Form.php:256](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Form.php#L256)

<a name="download"></a>
## class Caligrafy\Download

```php
namespace Caligrafy;

class Download
```

Source: [framework/core/Download.php:32](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Download.php#L32)

Class Download (2.19.0)
Route::download('/books.csv', 'list_books', ['as' =&gt; 'csv', 'filename' =&gt; 'books.csv']) answers a GET with the result
of a read-only capability as an attachment, without a controller:

- inputs: the query string and the route variables (which win), as the person who opens the link (Context::fromRequest(..., 'web')); the capability must be readOnly (a link must not change data)
- 'as' =&gt; 'csv' (default): RFC 4180 (CRLF, fields with a comma, a quote or a line break in double quotes, quotes doubled), UTF-8, the header row from the first row's keys; 'bom' =&gt; true starts the file with a UTF-8 BOM (Excel); text cells that start with = + - @ or a tab are prefixed with ' so that spreadsheets do not run them as formulas ('formulas' =&gt; true keeps them as they are); arrays in a cell are written as JSON, booleans as true / false. 'as' =&gt; 'json': the result, pretty-printed
- 'as' =&gt; 'zip' (2.22.0): the files the capability lists, in one ZIP archive streamed from a temporary file. Each item is a path (the file keeps its name) or ['file' =&gt; path, 'name' =&gt; 'folder/name in the archive']; a page of paginate() gives its rows. Paths are relative to 'root', a folder of the project (default 'public/uploads'): a file outside it, or missing, is left out, so a link never reaches other files. Duplicate names get " (2)". Images, video, audio and archives are stored as they are, other files compressed. No file at all: 404 (error 1005). Needs the PHP zip extension (in Caligrafy's Docker images and on Caligrafy Cloud)
- 'filename': a name, or a callable($result, $input) returning one (default: the capability's name)
- refusals as Route::page: a visitor is sent to sign in when Auth is active, else 403 (error 1006); forbidden 403; anything else 404 (error 1005)

### Constants

+ `FORMATS = array('csv', 'json', 'zip')`
+ `STORED = ...`

### Methods

+ [`Download::handle()`](#download-handle)
+ [`Download::columns()`](#download-columns)
+ [`Download::format()`](#download-format)
+ [`Download::root()`](#download-root)
+ [`Download::files()`](#download-files)
+ [`Download::entryName()`](#download-entryname)
+ [`Download::archive()`](#download-archive)
+ [`Download::rows()`](#download-rows)
+ [`Download::csvLines()`](#download-csvlines)
+ [`Download::csv()`](#download-csv)
+ [`Download::cell()`](#download-cell)
+ [`Download::filename()`](#download-filename)
+ [`Download::disposition()`](#download-disposition)

<a name="download-handle"></a>
#### `Download::handle()`

```php
public static function handle($capability, array $options = array(), $request = null)
```

Answers the current request (the route's closure)

**Parameters**

+ `$capability`
+ `$options` `array`, default `array()`
+ `$request`, default `null`

Source: [framework/core/Download.php:42](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Download.php#L42)

<a name="download-columns"></a>
#### `Download::columns()`

```php
public static function columns(array $options)
```

The 'columns' option (2.19.5): a list of column names, or null for the keys of the first row

**Parameters**

+ `$options` `array`

Source: [framework/core/Download.php:99](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Download.php#L99)

<a name="download-format"></a>
#### `Download::format()`

```php
public static function format(array $options)
```

_No doc comment._

**Parameters**

+ `$options` `array`

Source: [framework/core/Download.php:111](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Download.php#L111)

<a name="download-root"></a>
#### `Download::root()`

```php
public static function root(array $options)
```

The 'root' option of a ZIP (2.22.0): a folder of the project, 'public/uploads' by default, as an absolute path
(null when it does not exist)

**Parameters**

+ `$options` `array`

Source: [framework/core/Download.php:127](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Download.php#L127)

<a name="download-files"></a>
#### `Download::files()`

```php
public static function files($result, $root)
```

The files of a result for a ZIP: [absolute path =&gt; name in the archive], in order. Paths outside the root or
that are not files are left out; names are cleaned (no .., no leading /) and made unique

**Parameters**

+ `$result`
+ `$root`

Source: [framework/core/Download.php:142](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Download.php#L142)

<a name="download-entryname"></a>
#### `Download::entryName()`

```php
public static function entryName($name)
```

A name inside a ZIP: folders kept, without empty parts, . or .., control characters or a leading /

**Parameters**

+ `$name`

Source: [framework/core/Download.php:173](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Download.php#L173)

<a name="download-archive"></a>
#### `Download::archive()`

```php
public static function archive($result, array $options = array())
```

The ZIP of a result (2.22.0): a temporary file the caller removes, or null when no file can go in it.
Usable on its own, in a test: ['path' =&gt; ..., 'count' =&gt; ..., 'names' =&gt; [...]]

**Parameters**

+ `$result`
+ `$options` `array`, default `array()`

Source: [framework/core/Download.php:189](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Download.php#L189)

<a name="download-rows"></a>
#### `Download::rows()`

```php
public static function rows($result)
```

The rows of a result: a list of rows as it is, one row (an associative array) as a list of one, a list of
values as rows of one 'value' column

**Parameters**

+ `$result`

Source: [framework/core/Download.php:247](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Download.php#L247)

<a name="download-csvlines"></a>
#### `Download::csvLines()`

```php
public static function csvLines(array $rows, $bom = false, $escapeFormulas = true, ?array $columns = null)
```

The lines of a CSV file (each ends with CRLF): the header row from the first row's keys, then one line per row
in that order (a missing column is empty, an extra one left out)

**Parameters**

+ `$rows` `array`
+ `$bom`, default `false`
+ `$escapeFormulas`, default `true`
+ `$columns` `?array`, default `null`

Source: [framework/core/Download.php:270](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Download.php#L270)

<a name="download-csv"></a>
#### `Download::csv()`

```php
public static function csv(array $rows, $bom = false, $escapeFormulas = true, ?array $columns = null)
```

A whole CSV file

**Parameters**

+ `$rows` `array`
+ `$bom`, default `false`
+ `$escapeFormulas`, default `true`
+ `$columns` `?array`, default `null`

Source: [framework/core/Download.php:293](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Download.php#L293)

<a name="download-cell"></a>
#### `Download::cell()`

```php
public static function cell($value, $escapeFormulas = true)
```

One field of a CSV line, quoted when it must be (RFC 4180)

**Parameters**

+ `$value`
+ `$escapeFormulas`, default `true`

Source: [framework/core/Download.php:301](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Download.php#L301)

<a name="download-filename"></a>
#### `Download::filename()`

```php
public static function filename($option, $result, array $input, $default)
```

The file name: the option, or what its callable returns, without a path, quotes or control characters

**Parameters**

+ `$option`
+ `$result`
+ `$input` `array`
+ `$default`

Source: [framework/core/Download.php:319](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Download.php#L319)

<a name="download-disposition"></a>
#### `Download::disposition()`

```php
public static function disposition($filename)
```

Content-Disposition: attachment, with an ASCII name and the UTF-8 one (RFC 6266)

**Parameters**

+ `$filename`

Source: [framework/core/Download.php:330](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Download.php#L330)

<a name="webhook"></a>
## class Caligrafy\Webhook

```php
namespace Caligrafy;

class Webhook
```

Source: [framework/core/Webhook.php:24](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Webhook.php#L24)

Class Webhook (2.19.0)
Route::webhook('/stripe/events', 'record_payment', ['verify' =&gt; 'stripe']) answers the POSTs of another service with
a capability, without a controller:

- no CSRF token (the sender has no session): the signature of the body proves who sent it. 'verify' is required: 'stripe' checks the Stripe-Signature header with \Stripe\Webhook::constructEvent and the secret in the variable 'secret_env' names (default STRIPE_WEBHOOK_SECRET), with 'tolerance' seconds (default 300); a callable function (string $rawBody, array $headers): bool checks anything else (headers with lower-case names)
- the raw body (php://input) must be JSON; the capability gets ['event' =&gt; the decoded body], as the system (Context::system('webhook', $path)): declare public $rules = ['event' =&gt; 'required']
- answers: 200 {"received": true}; 400 for a bad signature or a body that is not JSON; the status of a ServiceError; 500 for anything else (written to the PHP error log)

### Public properties

+ `public static $logger = null`: callable|null replaces error_log() (tests)

### Methods

+ [`Webhook::handle()`](#webhook-handle)
+ [`Webhook::process()`](#webhook-process)
+ [`Webhook::verify()`](#webhook-verify)

<a name="webhook-handle"></a>
#### `Webhook::handle()`

```php
public static function handle($path, $capability, array $options)
```

Answers the current request (the route's closure)

**Parameters**

+ `$path`
+ `$capability`
+ `$options` `array`

Source: [framework/core/Webhook.php:32](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Webhook.php#L32)

<a name="webhook-process"></a>
#### `Webhook::process()`

```php
public static function process($path, $capability, array $options, $raw, array $headers)
```

What a webhook post leads to, without answering it (testable without a server)

**Parameters**

+ `$path`
+ `$capability`
+ `$options` `array`
+ `$raw`
+ `$headers` `array`

**Returns** `array`: [status, body]

Source: [framework/core/Webhook.php:47](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Webhook.php#L47)

<a name="webhook-verify"></a>
#### `Webhook::verify()`

```php
public static function verify($raw, array $headers, array $options)
```

Whether the body comes from the sender

**Parameters**

+ `$raw`
+ `$headers` `array`: lower-case names
+ `$options` `array`

**Returns** `true|string`: true, or why not

+ **@throws** \LogicException when the webhook is not set up (no secret, unknown 'verify')

Source: [framework/core/Webhook.php:84](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Webhook.php#L84)

<a name="uploads"></a>
## class Caligrafy\Uploads

```php
namespace Caligrafy;

class Uploads
```

Source: [framework/core/Uploads.php:28](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Uploads.php#L28)

Class Uploads (2.19.0)
A capability declares a file input with the rule `file`, an optional allow-list and an optional maximum size:

```
public $rules = ['cover' => 'required|file|extension,png;jpg|max_size,2mb'];
```

- web pages (Route::form) and REST (Route::capability, Route::capabilities) take the field from $_FILES once the caller is allowed to call the capability, check it (one file, the allow-list - never an executable type, see isAllowedUpload() - and the size), save it in public/uploads under a new random name with uploadFile() (the name the client sent is never used) and give handle() the saved file's public URL, a string. A value sent in that field without a file is dropped. The saved file is deleted when the call fails afterwards.
- MCP and the command line cannot send files: the field is a URL or a path string; its extension is checked against the allow-list.

The file rules (file, extension, max_size, required_file) are never given to GUMP: Service::validate() strips them.
A field with required_file (or required) and no file is invalid: 'The &lt;Field&gt; field needs a file' (2.19.1).
Without `extension` the allow-list is DEFAULT_UPLOAD_EXTENSIONS.

### Constants

+ `RULES = array('file', 'extension', 'max_size', 'required_file')`

### Methods

+ [`->__construct()`](#uploads-construct)
+ [`Uploads::fields()`](#uploads-fields)
+ [`Uploads::parse()`](#uploads-parse)
+ [`Uploads::required()`](#uploads-required)
+ [`Uploads::strip()`](#uploads-strip)
+ [`Uploads::bytes()`](#uploads-bytes)
+ [`Uploads::allowed()`](#uploads-allowed)
+ [`Uploads::check()`](#uploads-check)
+ [`Uploads::checkString()`](#uploads-checkstring)
+ [`->apply()`](#uploads-apply)
+ [`->discard()`](#uploads-discard)
+ [`->saved()`](#uploads-saved)

<a name="uploads-construct"></a>
#### `->__construct()`

```php
public function __construct(?array $files = null, ?callable $store = null, ?callable $delete = null)
```

_No doc comment._

**Parameters**

+ `$files` `?array`, default `null`
+ `$store` `?callable`, default `null`
+ `$delete` `?callable`, default `null`

Source: [framework/core/Uploads.php:44](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Uploads.php#L44)

<a name="uploads-fields"></a>
#### `Uploads::fields()`

```php
public static function fields(array $rules)
```

The file inputs of a set of rules

**Parameters**

+ `$rules` `array`

**Returns** `array`: field =&gt; ['extensions' =&gt; [..] or null, 'max' =&gt; bytes or null]

Source: [framework/core/Uploads.php:55](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Uploads.php#L55)

<a name="uploads-parse"></a>
#### `Uploads::parse()`

```php
public static function parse($rule)
```

The file part of one rule: null when the rule has no `file`

**Parameters**

+ `$rule`

Source: [framework/core/Uploads.php:70](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Uploads.php#L70)

<a name="uploads-required"></a>
#### `Uploads::required()`

```php
public static function required($rule)
```

Whether a file input must be sent: its rule has required_file, or required (2.19.1)

**Parameters**

+ `$rule`

Source: [framework/core/Uploads.php:95](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Uploads.php#L95)

<a name="uploads-strip"></a>
#### `Uploads::strip()`

```php
public static function strip(array $rules)
```

Rules without their file parts, for GUMP

**Parameters**

+ `$rules` `array`

Source: [framework/core/Uploads.php:111](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Uploads.php#L111)

<a name="uploads-bytes"></a>
#### `Uploads::bytes()`

```php
public static function bytes($size)
```

'2mb', '500kb', '1.5MB', '1g' or a number of bytes

**Parameters**

+ `$size`

Source: [framework/core/Uploads.php:132](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Uploads.php#L132)

<a name="uploads-allowed"></a>
#### `Uploads::allowed()`

```php
public static function allowed(array $spec)
```

The allow-list of a file input (never an executable type: isAllowedUpload() refuses those anyway)

**Parameters**

+ `$spec` `array`

Source: [framework/core/Uploads.php:144](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Uploads.php#L144)

<a name="uploads-check"></a>
#### `Uploads::check()`

```php
public static function check($file, array $spec)
```

What is wrong with an uploaded file (an entry of $_FILES), or null

**Parameters**

+ `$file`
+ `$spec` `array`

Source: [framework/core/Uploads.php:152](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Uploads.php#L152)

<a name="uploads-checkstring"></a>
#### `Uploads::checkString()`

```php
public static function checkString($value, array $spec)
```

What is wrong with a file input sent as a string (MCP, the command line), or null

**Parameters**

+ `$value`
+ `$spec` `array`

Source: [framework/core/Uploads.php:177](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Uploads.php#L177)

<a name="uploads-apply"></a>
#### `->apply()`

```php
public function apply(array $input, array $rules)
```

Replaces the file inputs of $input with the saved files of the request (web and REST)

**Parameters**

+ `$input` `array`: the inputs
+ `$rules` `array`: the capability's rules

**Returns** `array`: the inputs, with the public URL of each saved file

+ **@throws** ServiceError invalid, with a message per file field

Source: [framework/core/Uploads.php:196](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Uploads.php#L196)

<a name="uploads-discard"></a>
#### `->discard()`

```php
public function discard()
```

Deletes the files apply() saved (the call failed afterwards)

Source: [framework/core/Uploads.php:231](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Uploads.php#L231)

<a name="uploads-saved"></a>
#### `->saved()`

```php
public function saved()
```

The URLs apply() saved

Source: [framework/core/Uploads.php:242](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Uploads.php#L242)

<a name="throttle"></a>
## class Caligrafy\Throttle

```php
namespace Caligrafy;

class Throttle
```

Source: [framework/core/Throttle.php:19](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Throttle.php#L19)

Class Throttle (2.19.0)

```
$throttle = new Throttle(5, 900);          // 5 failures within 15 minutes lock the key for the rest of them
if ($throttle->locked($key)) ...; $throttle->fail($key); $throttle->clear($key);
```

The counts are kept in the Cache (CACHE_STORE: the caligrafy_cache table or a private folder, shared by every
session, so that a new cookie does not start again), or in the session when the cache is off.
Each failure keeps the count for $seconds more.

### Public properties

+ `public $max`: int
+ `public $seconds`: int

### Methods

+ [`->__construct()`](#throttle-construct)
+ [`Throttle::key()`](#throttle-key)
+ [`->limitedTo()`](#throttle-limitedto)
+ [`->locked()`](#throttle-locked)
+ [`->failures()`](#throttle-failures)
+ [`->fail()`](#throttle-fail)
+ [`->clear()`](#throttle-clear)

<a name="throttle-construct"></a>
#### `->__construct()`

```php
public function __construct($max = 5, $seconds = 900, ?array $store = null)
```

_No doc comment._

**Parameters**

+ `$max`, default `5`
+ `$seconds`, default `900`
+ `$store` `?array`, default `null`

Source: [framework/core/Throttle.php:30](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Throttle.php#L30)

<a name="throttle-key"></a>
#### `Throttle::key()`

```php
public static function key($scope, $ip, $username)
```

A key for a person at an address: the IP and the username (lower case), hashed

**Parameters**

+ `$scope`
+ `$ip`
+ `$username`

Source: [framework/core/Throttle.php:40](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Throttle.php#L40)

<a name="throttle-limitedto"></a>
#### `->limitedTo()`

```php
public function limitedTo($max)
```

The same counts and window with another limit (2.19.6: Route::auth's attemptsPerUser)

**Parameters**

+ `$max`

Source: [framework/core/Throttle.php:48](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Throttle.php#L48)

<a name="throttle-locked"></a>
#### `->locked()`

```php
public function locked($key)
```

Whether the key failed $max times within the window

**Parameters**

+ `$key`

Source: [framework/core/Throttle.php:58](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Throttle.php#L58)

<a name="throttle-failures"></a>
#### `->failures()`

```php
public function failures($key)
```

The failures of the key within the window

**Parameters**

+ `$key`

Source: [framework/core/Throttle.php:66](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Throttle.php#L66)

<a name="throttle-fail"></a>
#### `->fail()`

```php
public function fail($key)
```

Counts one failure; returns the failures of the key

**Parameters**

+ `$key`

Source: [framework/core/Throttle.php:75](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Throttle.php#L75)

<a name="throttle-clear"></a>
#### `->clear()`

```php
public function clear($key)
```

Forgets the failures of the key (a success)

**Parameters**

+ `$key`

Source: [framework/core/Throttle.php:85](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Throttle.php#L85)

<a name="errors"></a>
## class Caligrafy\Errors

```php
namespace Caligrafy;

class Errors extends \stdClass
```

Source: [framework/core/Errors.php:18](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Errors.php#L18)

The Errors Class is the dictionary of all the error messages in the system

### Constants

+ `GENERIC_MESSAGE = '[ERROR 500] Internal Server Error'`

### Methods

+ [`Errors::status()`](#errors-status)
+ [`Errors::raise()`](#errors-raise)
+ [`Errors::handle()`](#errors-handle)
+ [`Errors::shutdown()`](#errors-shutdown)
+ [`Errors::get()`](#errors-get)
+ [`Errors::set()`](#errors-set)

<a name="errors-status"></a>
#### `Errors::status()`

```php
public static function status($errorCode)
```

Get the HTTP status code of an error code

**Parameters**

+ `$errorCode` `int`: identifies the error code

**Returns** `int`: HTTP status code (500 when the error code is unknown)

Source: [framework/core/Errors.php:78](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Errors.php#L78)

<a name="errors-raise"></a>
#### `Errors::raise()`

```php
public static function raise($errorCode, $detail = null)
```

Creates the exception of a framework error and sets its HTTP status code right away, so that the status is
correct even when the exception is caught by an application that only echoes the message

**Parameters**

+ `$errorCode` `int`: identifies the error code
+ `$detail` `string|null`, default `null`: why, added to the message: '[ERROR 1004] Access Denied: &lt;detail&gt;'

**Returns** `\Exception`: to be thrown

Source: [framework/core/Errors.php:89](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Errors.php#L89)

<a name="errors-handle"></a>
#### `Errors::handle()`

```php
public static function handle(\Throwable $e, $hideUnknown = false)
```

Sends an error response: HTTP status code and the error text (HTML requests) or
{"error": {"code": ..., "message": ...}} (requests that want JSON)
Framework errors keep their message. Other exceptions caught by the application keep theirs too
unless $hideUnknown is true (uncaught exceptions), in which case the message is only shown when APP_DEBUG is true

**Parameters**

+ `$e` `\Throwable`: the error
+ `$hideUnknown` `bool`, default `false`: hides the message of errors that are not framework errors unless APP_DEBUG is true

Source: [framework/core/Errors.php:105](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Errors.php#L105)

<a name="errors-shutdown"></a>
#### `Errors::shutdown()`

```php
public static function shutdown()
```

Shutdown function: turns PHP fatal errors into a 500 response (message only when APP_DEBUG is true)

Source: [framework/core/Errors.php:121](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Errors.php#L121)

<a name="errors-get"></a>
#### `Errors::get()`

```php
public static function get($errorCode)
```

Get error message based on error code

**Parameters**

+ `$errorCode` `string`: identifies the error code

**Returns** `string`: identifying the error message

Source: [framework/core/Errors.php:169](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Errors.php#L169)

<a name="errors-set"></a>
#### `Errors::set()`

```php
public static function set($errorMessage, $errorCode)
```

_No doc comment._

**Parameters**

+ `$errorMessage`
+ `$errorCode`

Source: [framework/core/Errors.php:173](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Errors.php#L173)

<a name="flash"></a>
## class Caligrafy\Flash

```php
namespace Caligrafy;

class Flash
```

Source: [framework/core/Flash.php:20](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Flash.php#L20)

Class Flash (2.19.0)
Route::form() puts the field errors, the old input and a message here before it redirects; the page of the next
request reads them with the view helpers errors($field), old($field) and flash($key), then they are gone.
Route::run() ages them when there are some: what the previous request put becomes this request's, and leaves the
session (without Route::run, the first read does).

Kept in $_SESSION['__flash'] as ['errors' =&gt; [field =&gt; message], 'old' =&gt; [field =&gt; value], 'messages' =&gt; [key =&gt; text]].

### Constants

+ `KEY = '__flash'`

### Methods

+ [`Flash::age()`](#flash-age)
+ [`Flash::put()`](#flash-put)
+ [`Flash::message()`](#flash-message)
+ [`Flash::get()`](#flash-get)
+ [`Flash::reset()`](#flash-reset)

<a name="flash-age"></a>
#### `Flash::age()`

```php
public static function age()
```

Moves what the previous request put into this request (Route::run calls it once)

Source: [framework/core/Flash.php:30](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Flash.php#L30)

<a name="flash-put"></a>
#### `Flash::put()`

```php
public static function put($key, $value)
```

Keeps a value for the next request

**Parameters**

+ `$key` `string`: errors, old or messages
+ `$value`

Source: [framework/core/Flash.php:42](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Flash.php#L42)

<a name="flash-message"></a>
#### `Flash::message()`

```php
public static function message($key, $text)
```

Keeps a message for the next request: Flash::message('success', 'Book added')

**Parameters**

+ `$key`
+ `$text`

Source: [framework/core/Flash.php:56](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Flash.php#L56)

<a name="flash-get"></a>
#### `Flash::get()`

```php
public static function get($key, $default = null)
```

What the previous request put (errors, old or messages)

**Parameters**

+ `$key`
+ `$default`, default `null`

Source: [framework/core/Flash.php:66](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Flash.php#L66)

<a name="flash-reset"></a>
#### `Flash::reset()`

```php
public static function reset()
```

Forgets what this request read (tests)

Source: [framework/core/Flash.php:77](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Flash.php#L77)

<a name="context"></a>
## class Caligrafy\Context

```php
namespace Caligrafy;

class Context
```

Source: [framework/core/Context.php:23](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Context.php#L23)

Class Context
Built by the channel adapters (web pages, REST, MCP, CLI) and read by the services: a service never looks at the
request, the session or the headers itself.

The actor is one of:

- user: a signed-in user (session), or the owner of a token
- token: a personal access token (Tokens), with its scopes
- key: the legacy API key (every generated key is the same key: full access, as before 2.1)
- cli: a script or the command line (full access); a scheduled job is a system context on this channel
- guest: nobody: only public capabilities

### Constants

+ `CHANNELS = array('web', 'rest', 'mcp', 'cli')`

### Public properties

+ `public static $levelAttribute = 'permissions'`: Name of the users column that holds the permission level compared with a capability's level (Auth::guard)
+ `public $channel`: string web, rest, mcp or cli
+ `public $viaAction = false`: bool the call comes from Route::action() (2.21.0): the only way to a webOnly capability
+ `public $user`: object|null the user model (signed in, or the owner of the token)
+ `public $token`: array|null the token row (id, name, scopes, user_id...)

### Methods

+ [`->__construct()`](#context-construct)
+ [`Context::cli()`](#context-cli)
+ [`Context::local()`](#context-local)
+ [`Context::system()`](#context-system)
+ [`Context::guest()`](#context-guest)
+ [`Context::forToken()`](#context-fortoken)
+ [`Context::fromRequest()`](#context-fromrequest)
+ [`->authenticated()`](#context-authenticated)
+ [`->allows()`](#context-allows)
+ [`->level()`](#context-level)
+ [`->userId()`](#context-userid)
+ [`->actorType()`](#context-actortype)
+ [`->actorId()`](#context-actorid)

<a name="context-construct"></a>
#### `->__construct()`

```php
public function __construct($channel = 'cli', $user = null, $token = null, $full = false)
```

_No doc comment._

**Parameters**

+ `$channel`, default `'cli'`
+ `$user`, default `null`
+ `$token`, default `null`
+ `$full`, default `false`

Source: [framework/core/Context.php:53](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Context.php#L53)

<a name="context-cli"></a>
#### `Context::cli()`

```php
public static function cli()
```

The context of the command line and of scripts: full access

Source: [framework/core/Context.php:67](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Context.php#L67)

<a name="context-local"></a>
#### `Context::local()`

```php
public static function local($channel)
```

Full access through another channel for a local process (php caligrafer.php mcp without a token)

**Parameters**

+ `$channel`

Source: [framework/core/Context.php:75](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Context.php#L75)

<a name="context-system"></a>
#### `Context::system()`

```php
public static function system($type, $name)
```

Full access for work the system does on its own, such as a scheduled job: the audit log records the actor type
(schedule) and its name (the job's)

**Parameters**

+ `$type` `string`: the actor type, e.g. schedule
+ `$name` `string`: the actor id, e.g. the job's name

Source: [framework/core/Context.php:88](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Context.php#L88)

<a name="context-guest"></a>
#### `Context::guest()`

```php
public static function guest($channel = 'rest')
```

The context of nobody: only public capabilities

**Parameters**

+ `$channel`, default `'rest'`

Source: [framework/core/Context.php:99](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Context.php#L99)

<a name="context-fortoken"></a>
#### `Context::forToken()`

```php
public static function forToken(array $token, $channel = 'rest')
```

The context of a personal access token: its scopes, and its owner when it has one and authentication is on

**Parameters**

+ `$token` `array`
+ `$channel`, default `'rest'`

Source: [framework/core/Context.php:107](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Context.php#L107)

<a name="context-fromrequest"></a>
#### `Context::fromRequest()`

```php
public static function fromRequest(Request $request, $channel = 'rest')
```

The context of the current HTTP request: a token (Authorization: Bearer cq_...), else the legacy API key, else the
signed-in user, else a guest

**Parameters**

+ `$request` `Request`: the request
+ `$channel` `string`, default `'rest'`: web, rest or mcp

Source: [framework/core/Context.php:122](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Context.php#L122)

<a name="context-authenticated"></a>
#### `->authenticated()`

```php
public function authenticated()
```

Whether someone is acting (anything but a guest)

Source: [framework/core/Context.php:150](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Context.php#L150)

<a name="context-allows"></a>
#### `->allows()`

```php
public function allows($scope, $level = 0)
```

Whether this context may use a capability that needs a scope and a minimum user level

- the CLI and the legacy key: always
- a token: it must grant the scope, and its owner (if any) must have the level
- a signed-in user: the level (users have every scope their level allows)

**Parameters**

+ `$scope` `string`: e.g. books:write ('' = no scope needed)
+ `$level` `int`, default `0`: minimum value of the users permission column (0 = any signed-in user)

Source: [framework/core/Context.php:163](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Context.php#L163)

<a name="context-level"></a>
#### `->level()`

```php
public function level()
```

The permission level of the user (0 when there is none)

Source: [framework/core/Context.php:186](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Context.php#L186)

<a name="context-userid"></a>
#### `->userId()`

```php
public function userId()
```

The user id, when a user acts (signed in or owner of the token)

Source: [framework/core/Context.php:195](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Context.php#L195)

<a name="context-actortype"></a>
#### `->actorType()`

```php
public function actorType()
```

user, token, key, cli or guest (as written to the audit log)

Source: [framework/core/Context.php:203](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Context.php#L203)

<a name="context-actorid"></a>
#### `->actorId()`

```php
public function actorId()
```

The token id or the user id, as a string (null for the CLI, the legacy key and guests)

Source: [framework/core/Context.php:220](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Context.php#L220)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Route -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Caligrafy\Route

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Part of [Routing and requests](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing).

<a name="route"></a>
```php
namespace Caligrafy;

class Route extends \stdClass
```

Source: [framework/core/Route.php:20](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L20)

Class that builds the routing logic of the framework

## Constants

+ `EXAMPLE_CONTROLLERS_NAMESPACE = 'Caligrafy\\Controllers'`: Namespace of the example controllers shipped in application/controllers/core (AIController, AuthController...)

## Public properties

+ `public static $currentRoute`: string $currentRoute defines the currently run route
+ `public static $currentBind`: string $currentBind defines variables bound to the route

## Methods

+ [`Route::run()`](#route-run)
+ [`Route::evaluate()`](#route-evaluate)
+ [`Route::bind()`](#route-bind)
+ [`Route::execute()`](#route-execute)
+ [`Route::resolveController()`](#route-resolvecontroller)
+ [`Route::get()`](#route-get)
+ [`Route::post()`](#route-post)
+ [`Route::put()`](#route-put)
+ [`Route::delete()`](#route-delete)
+ [`Route::capability()`](#route-capability)
+ [`Route::page()`](#route-page)
+ [`Route::pages()`](#route-pages)
+ [`Route::action()`](#route-action)
+ [`Route::bots()`](#route-bots)
+ [`Route::capabilities()`](#route-capabilities)
+ [`Route::notifications()`](#route-notifications)
+ [`Route::snap()`](#route-snap)
+ [`Route::mcp()`](#route-mcp)
+ [`Route::form()`](#route-form)
+ [`Route::auth()`](#route-auth)
+ [`Route::webhook()`](#route-webhook)
+ [`Route::download()`](#route-download)
+ [`Route::redirect()`](#route-redirect)
+ [`Route::withQuery()`](#route-withquery)
+ [`Route::redirectTarget()`](#route-redirecttarget)
+ [`Route::isWebhook()`](#route-iswebhook)
+ [`Route::isMcp()`](#route-ismcp)
+ [`Route::routes()`](#route-routes)
+ [`Route::reset()`](#route-reset)
+ [`Route::handler()`](#route-handler)

<a name="route-run"></a>
### `Route::run()`

```php
public static function run()
```

Runs the routes based upon a request

Source: [framework/core/Route.php:102](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L102)

<a name="route-evaluate"></a>
### `Route::evaluate()`

```php
public static function evaluate()
```

Evaluates the route and binds it with variables from the request

Source: [framework/core/Route.php:127](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L127)

<a name="route-bind"></a>
### `Route::bind()`

```php
public static function bind()
```

Binding the route variables

Source: [framework/core/Route.php:198](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L198)

<a name="route-execute"></a>
### `Route::execute()`

```php
public static function execute()
```

Executing the routing

Source: [framework/core/Route.php:215](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L215)

<a name="route-resolvecontroller"></a>
### `Route::resolveController()`

```php
public static function resolveController($name)
```

Resolves the controller part of a 'Controller@action' route to a declared class name

- fully qualified names are accepted, with or without a leading backslash: 'Shop\OrderController', '\Shop\OrderController'
- a declared class always wins (a project's own global AIController is used as is)
- a short name that is not a declared class falls back to the framework example controllers namespace (Caligrafy\Controllers), so routes written before 1.6 such as 'AIController@query' keep working

**Parameters**

+ `$name` `string`: defines the controller part of the route

**Returns** `string|null`: the class name, or null when no such controller exists

Source: [framework/core/Route.php:263](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L263)

<a name="route-get"></a>
### `Route::get()`

```php
public static function get($route, $method = null)
```

GET http method handler

**Parameters**

+ `$route` `string`: defines the uri
+ `$method` `object`, default `null`: defines the method to be used, it could be a String or a callback function

Source: [framework/core/Route.php:283](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L283)

<a name="route-post"></a>
### `Route::post()`

```php
public static function post($route, $method = null)
```

POST http method handler

**Parameters**

+ `$route` `string`: defines the uri
+ `$method` `object`, default `null`: defines the method to be used, it could be a String or a callback function

Source: [framework/core/Route.php:294](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L294)

<a name="route-put"></a>
### `Route::put()`

```php
public static function put($route, $method = null)
```

PUT http method handler

**Parameters**

+ `$route` `string`: defines the uri
+ `$method` `object`, default `null`: defines the method to be used, it could be a String or a callback function

Source: [framework/core/Route.php:305](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L305)

<a name="route-delete"></a>
### `Route::delete()`

```php
public static function delete($route, $method = null)
```

DELETE http method handler

**Parameters**

+ `$route` `string`: defines the uri
+ `$method` `object`, default `null`: defines the method to be used, it could be a String or a callback function

Source: [framework/core/Route.php:316](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L316)

<a name="route-capability"></a>
### `Route::capability()`

```php
public static function capability($method, $route, $name)
```

Maps a route to a capability (REST): Route::capability('POST', '/books', 'create_book')
The route variables ({id}) become inputs of the capability. See Caligrafy\Rest for the request and response format.

**Parameters**

+ `$method` `string`: GET, POST, PUT or DELETE
+ `$route` `string`: the uri
+ `$name` `string`: the capability name

Source: [framework/core/Route.php:329](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L329)

<a name="route-page"></a>
### `Route::page()`

```php
public static function page($route, $view, array $options = array())
```

A page: renders a view through the framework's page controller, which gives every page who is signed in and,
optionally, an access rule and data from capabilities (pages never read models):

```
Route::page('/books', 'Books/index');
Route::page('/books/{id}', 'Books/show', ['data' => ['book' => 'get_book']]);
Route::page('/admin/books', 'Books/admin', ['level' => 1, 'data' => ['books' => 'list_books']]);
```

Options: 'signedIn' (bool), 'level' (int), 'data' (name =&gt; read-only capability, or [capability, inputs]),
'with' (fixed values), 'notFound' (a view shown with a 404 when a data capability finds nothing);
2.20.0: 'visitorsOnly' (a path: signed-in people are sent there), 'comeBack' (true: a visitor goes to
/login?return=&lt;this page&gt;), 'query' (the names of the query string the view gets)

**Parameters**

+ `$route` `string`: the uri
+ `$view` `string`: the view, as for view()
+ `$options` `array`, default `array()`: see PageController::render()

Source: [framework/core/Route.php:352](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L352)

<a name="route-pages"></a>
### `Route::pages()`

```php
public static function pages()
```

The pages declared with Route::page (2.24.0): each with its route, its view and its options (its data
capabilities), so that a capability can be shown through the page designed for it

**Returns** `array`: of ['route' =&gt; 'books/{id}', 'view' =&gt; 'Bookshelf/book', 'options' =&gt; [...]]

Source: [framework/core/Route.php:363](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L363)

<a name="route-action"></a>
### `Route::action()`

```php
public static function action($route, $capability, array $options = array())
```

A request answered by a web-only capability (2.21.0, Caligrafy\Action): for what Route::page and Route::form
cannot say, such as a sign-in between two sites, a gate or a payment page. The capability is declared
#[Capability(..., webOnly: true)] and may return a Caligrafy\Web.

```
Route::action('/connect', 'cloud_connect');
Route::action('/unlock/{name}', 'unlock_app', ['method' => 'POST']);
```

Options: 'method' ('GET' by default, 'POST', 'PUT', 'DELETE' or a list), 'signedIn', 'level', 'comeBack',
'visitorsOnly' (as Route::page), 'back', 'error' and 'signIn' (as Route::form, for a refusal it does not answer)

**Parameters**

+ `$route`
+ `$capability`
+ `$options` `array`, default `array()`

Source: [framework/core/Route.php:377](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L377)

<a name="route-bots"></a>
### `Route::bots()`

```php
public static function bots()
```

The data routes of the Watson bot apps (2.21.0): the addresses public/&lt;app&gt; of a bot calls

Source: [framework/core/Route.php:391](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L391)

<a name="route-capabilities"></a>
### `Route::capabilities()`

```php
public static function capabilities($prefix = '/capabilities')
```

Exposes every capability under a prefix: GET {prefix} lists what the caller may call (with the input schemas),
POST {prefix}/{name} calls one. The JS client of the Vue apps and the SPA (php caligrafer.php client) uses it.

**Parameters**

+ `$prefix` `string`, default `'/capabilities'`: the uri prefix

Source: [framework/core/Route.php:403](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L403)

<a name="route-notifications"></a>
### `Route::notifications()`

```php
public static function notifications()
```

The two pages notification emails link to (2.15.0, Notify): /notify/confirm/{token} confirms an address,
/notify/unsubscribe turns the user's emails off from a signed link, also as the one-click POST of mail providers
(List-Unsubscribe-Post: the signature replaces the CSRF token). Each answers a short page

Source: [framework/core/Route.php:418](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L418)

<a name="route-snap"></a>
### `Route::snap()`

```php
public static function snap(array $options = array())
```

Snap Cards and the assistant (2.23.0, Caligrafy\Snap): every capability of the app as a card, and an assistant
that answers with them, in one line of web.php:

```
Route::snap();
Route::snap(['assistant' => '/help', 'cards' => '/cards']);
```

It declares, for the signed-in person:

```
/assistant              Home (what needs you, insights, things to browse, shortcuts) and the task space
/assistant/ask          what they typed, said, attached or clicked (snap_ask)
/assistant/noticed      what the assistant noticed, and their routines (a settings page)
/snap                   every card they may use (a gallery), /snap/c/{capability} one card at its own address
/snap/run, /snap/call/  a card sent (snap_run), and the snap_* capabilities the pages call
```

The tables come with php caligrafer.php platform install; card hints are in application/config/snap.php; the
assistant uses Claude when ANTHROPIC_API_KEY is set (else it answers from the cards' names, without a model).
Changes only ever run from a Confirm the person clicks (Caligrafy\Snap\Consent).

**Parameters**

+ `$options` `array`, default `array()`: 'assistant' (the path of the assistant, '/assistant'), 'cards' (the path of the cards, '/snap')

Source: [framework/core/Route.php:448](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L448)

<a name="route-mcp"></a>
### `Route::mcp()`

```php
public static function mcp($route = '/mcp')
```

Exposes the capabilities to AI agents over MCP (Streamable HTTP) at a uri: Route::mcp('/mcp')
Agents authenticate with a personal access token and see the capabilities its scopes allow.

**Parameters**

+ `$route` `string`, default `'/mcp'`: the uri of the MCP endpoint

Source: [framework/core/Route.php:490](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L490)

<a name="route-form"></a>
### `Route::form()`

```php
public static function form($route, $capability, array $options = array())
```

A form without a controller (2.19.0, Caligrafy\Form): the form's POST calls a capability, then redirects

```
Route::page('/books/new', 'Books/new');
Route::form('/books', 'create_book', ['success' => '/books/{id}', 'flash' => 'Book added']);
Route::form('/books/{id}', 'update_book', ['method' => 'PUT', 'success' => '/books/{id}']);
```

GET stays a Route::page. Options: 'method' (POST, PUT or DELETE, or a list; default POST), 'success' (a path with
{placeholders} from the result and the route, or a callable($result) returning one; default back), 'flash' (a
message for flash('success'), or [key =&gt; message]), 'back' (where invalid input goes; default the Referer of this
site), 'error' (the message for flash('error') instead of the capability's), 'signIn' (default /login);
2.20.0: 'visitorsOnly' (a path: signed-in people are sent there), 'same' ([field =&gt; [other field, message]]),
'accepted' ([field =&gt; message]: a box that must be ticked), 'inputs' (values only the server sets: an array or a
callable($input)), 'signsIn' (the field of the answer that holds the id of the person to sign in), 'signsInWith'
(how: 'password' by default, what AuthRoutes::signedInBy() answers).
'success' may be a full address, or a callable returning one (a payment page).
Invalid input goes back with errors($field), old($field) and flash('error') for the next page. JSON requests get
the REST answer.

**Parameters**

+ `$route`
+ `$capability`
+ `$options` `array`, default `array()`

Source: [framework/core/Route.php:515](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L515)

<a name="route-auth"></a>
### `Route::auth()`

```php
public static function auth(array $options = array())
```

The sign-in pages without a controller (2.19.0, Caligrafy\AuthRoutes): /login, /logout, /register,
/notAuthorized and, with 'passkeys' =&gt; true, the passkey endpoints. Needs Auth::authentication(...) before it.

```
Route::auth(['home' => '/books']);
```

Options: prefix, home ('/'), logout ('/'), register (true, false or the capability), attempts (5), lock (900
seconds), views, passkeys (false), identifier ('username', or the users column people sign in with: 'email'),
signInAfterRegister (false: true signs the new account in and goes 'home'). See AuthRoutes.

**Parameters**

+ `$options` `array`, default `array()`

Source: [framework/core/Route.php:534](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L534)

<a name="route-webhook"></a>
### `Route::webhook()`

```php
public static function webhook($route, $capability, array $options = array())
```

Events another service posts (2.19.0, Caligrafy\Webhook): POST only, no CSRF token, the signature checked

```
Route::webhook('/stripe/events', 'record_payment', ['verify' => 'stripe', 'secret_env' => 'STRIPE_WEBHOOK_SECRET']);
Route::webhook('/hooks/github', 'record_push', ['verify' => fn ($raw, $headers) => hash_equals(...)]);
```

The capability gets ['event' =&gt; the decoded JSON body] as the system (Context::system('webhook', $path)).

**Parameters**

+ `$route`
+ `$capability`
+ `$options` `array`, default `array()`

Source: [framework/core/Route.php:545](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L545)

<a name="route-download"></a>
### `Route::download()`

```php
public static function download($route, $capability, array $options = array())
```

A read-only capability's result as a file (2.19.0, Caligrafy\Download): GET

```
Route::download('/books.csv', 'list_books', ['as' => 'csv', 'filename' => 'books.csv']);
Route::download('/photos.zip', 'list_photo_files', ['as' => 'zip', 'root' => 'public/uploads/photos']);  // 2.22.0
```

Options: 'as' (csv, json or zip: the files the capability lists, under 'root', default public/uploads), 'columns' (2.19.5: the header row, written even with no row), 'filename' (a name or a
callable($result, $input)), 'bom' (bool), 'formulas' (keep
cells that start with = + - @ as they are), 'signIn'. Refusals as Route::page; inputs to fix answer 422 (2.19.5).

**Parameters**

+ `$route`
+ `$capability`
+ `$options` `array`, default `array()`

Source: [framework/core/Route.php:563](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L563)

<a name="route-redirect"></a>
### `Route::redirect()`

```php
public static function redirect($from, $to, $status = 302, array $options = array())
```

A GET that sends the visitor elsewhere (2.19.0): no closure, no controller

```
Route::redirect('/', '/books');
Route::redirect('/old/books/{id}', '/books/{id}', 301);
```

{name} in $to takes the route variable of $from (url-encoded). $to is a path of this site or a full http(s) address.

**Parameters**

+ `$from`
+ `$to`
+ `$status` `int`, default `302`: 301, 302 (default), 303, 307 or 308
+ `$options` `array`, default `array()`: 'keepQuery' (2.20.0, true: the query string of the request goes along)

Source: [framework/core/Route.php:578](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L578)

<a name="route-withquery"></a>
### `Route::withQuery()`

```php
public static function withQuery($target, array $query)
```

An address with a query string added (2.20.0, 'keepQuery'); the server's rewrite adds 'uri', which never goes along

**Parameters**

+ `$target`
+ `$query` `array`

Source: [framework/core/Route.php:601](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L601)

<a name="route-redirecttarget"></a>
### `Route::redirectTarget()`

```php
public static function redirectTarget($to, array $variables = array())
```

Where a Route::redirect sends: $to with its {placeholders} filled from the route variables (url-encoded)

**Parameters**

+ `$to`
+ `$variables` `array`, default `array()`

Source: [framework/core/Route.php:618](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L618)

<a name="route-iswebhook"></a>
### `Route::isWebhook()`

```php
public static function isWebhook($uri)
```

Whether a uri is the address of a Route::webhook (no CSRF token: its signature is checked)

**Parameters**

+ `$uri`

Source: [framework/core/Route.php:626](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L626)

<a name="route-ismcp"></a>
### `Route::isMcp()`

```php
public static function isMcp($uri)
```

Whether a uri is an MCP endpoint (Route::mcp): Request skips the session CSRF check for its POST, since
Mcp\Http answers 401 to a request without a personal access token and never uses the session (2.19.1)

**Parameters**

+ `$uri`

Source: [framework/core/Route.php:641](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L641)

<a name="route-routes"></a>
### `Route::routes()`

```php
public static function routes()
```

The routes declared so far: [['method' =&gt; 'GET', 'route' =&gt; 'books/{id}'], ...]

Source: [framework/core/Route.php:655](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L655)

<a name="route-reset"></a>
### `Route::reset()`

```php
public static function reset()
```

Forgets every route (tests)

Source: [framework/core/Route.php:667](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L667)

<a name="route-handler"></a>
### `Route::handler()`

```php
public static function handler($method, $route)
```

The closure (or Controller@action) of a declared route, without a request (tests): Route::handler('POST', '/books')

**Parameters**

+ `$method`
+ `$route`

Source: [framework/core/Route.php:676](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Route.php#L676)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-AuthRoutes -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Caligrafy\AuthRoutes

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Part of [Routing and requests](https://github.com/caligrafy/caligrafy-quill/wiki/API-Routing).

<a name="authroutes"></a>
```php
namespace Caligrafy;

class AuthRoutes
```

Source: [framework/core/AuthRoutes.php:40](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L40)

Class AuthRoutes (2.19.0)
Route::auth() (after Auth::authentication('User', 'users') in web.php) registers, with the views of the
authentication module (application/views/Auth/login.pug and register.pug):

```
GET  /login           the sign-in page (a signed-in person goes to 'home')
POST /login           signs in: the username (or 'identifier') and passcode fields, checked with the model's
                      findByUsername() (another identifier: its findBy($column, $value), else the query builder)
                      and verifyPassword() (an old encrypted passcode is upgraded to a hash); a new session id
                      (session_regenerate_id(true)) and a new CSRF token; then 'home'
GET|POST /logout      signs out: a new session id and CSRF token, then 'logout'
GET  /notAuthorized   where Auth::guard() sends people below the level a page needs (403)
GET|POST /register    the sign-up page and the register_user capability (every input its rules declare), then the
                      sign-in page, or signed in and 'home' with 'signInAfterRegister' ('register' => false: none)
with 'passkeys' => true, the JSON endpoints of Caligrafy\Passkey (the passkeys table of the face login recipe, the
page sends the X-CSRF-Token header; public/js/services/passkey.js in the browser):
POST /passkey/register/options, /passkey/register (signed in), /passkey/login/options, /passkey/login
```

Failed sign-ins are counted per IP and username (Throttle, in the Cache): after 'attempts' (5) within 'lock' seconds
(900) that username is refused from that address (429) until the window ends.
Options: prefix (''), home ('/'), logout ('/'), register (true, or the name of the capability), attempts, lock,
views (['login' =&gt; 'Auth/login', 'register' =&gt; 'Auth/register']), passkeys (false), identifier ('username': the
users column people sign in with and the name of its field, 'email' for instance), signInAfterRegister (false),
attemptsPerUser (2.19.6: failures of one username from any address before it is locked, 0 = off), level (2.19.5: the lowest permission level that may sign in, 0 by default; below it, the sign-in is refused like a
wrong password), messages (what sign-in and sign-up say: 'invalid', 'locked' ({minutes} is the wait), 2.19.3; 'mismatch',
'register_invalid', 'register_taken', 'registered', 2.19.4; see AuthRoutes::MESSAGES).
A failed sign-in shows the page again with what the person typed in the identifier field (never the password).
A JSON request (Accept: application/json) gets JSON answers and needs the X-CSRF-Token header.
Not provided by the framework, so refused with a LogicException: 'face' (the face login recipe has its own
controller and tables) and 'reset' (password reset: the users table has no email address).

## Constants

+ `RETURN_TO = '__auth_return'`: the session key of the page to go back to after signing in (2.20.0)
+ `SIGNED_IN_BY = '__auth_signed_in_by'`: the session key of how this session signed in (2.21.3)
+ `DUMMY_HASH = '$2y$10$B0NLUgDUK3CbImwrVfa/FuOtSOKrb7DZTGG3USPSF4Comn4cy5RtG'`
+ `MESSAGES = ...`

## Public properties

+ `public static $signUp = null`: bool|null whether a Route::auth of this request has a sign-up page (null: no Route::auth)
+ `public static $regenerate = null`: callable|null replaces session_regenerate_id(true) (tests)

## Methods

+ [`AuthRoutes::signUpOpen()`](#authroutes-signupopen)
+ [`AuthRoutes::mayEnter()`](#authroutes-mayenter)
+ [`AuthRoutes::options()`](#authroutes-options)
+ [`AuthRoutes::register()`](#authroutes-register)
+ [`AuthRoutes::attempt()`](#authroutes-attempt)
+ [`AuthRoutes::signIn()`](#authroutes-signin)
+ [`AuthRoutes::rememberSignIn()`](#authroutes-remembersignin)
+ [`AuthRoutes::signedInBy()`](#authroutes-signedinby)
+ [`AuthRoutes::signOut()`](#authroutes-signout)
+ [`AuthRoutes::regenerate()`](#authroutes-regenerate)
+ [`AuthRoutes::finder()`](#authroutes-finder)
+ [`AuthRoutes::registerInput()`](#authroutes-registerinput)
+ [`AuthRoutes::registration()`](#authroutes-registration)
+ [`AuthRoutes::ip()`](#authroutes-ip)
+ [`AuthRoutes::safeReturn()`](#authroutes-safereturn)

<a name="authroutes-signupopen"></a>
### `AuthRoutes::signUpOpen()`

```php
public static function signUpOpen()
```

Whether the site has a sign-up page (2.19.6, the top bar and the sign-in page): true without Route::auth, and when
a Route::auth of the request has one; false when every Route::auth says 'register' =&gt; false

Source: [framework/core/AuthRoutes.php:67](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L67)

<a name="authroutes-mayenter"></a>
### `AuthRoutes::mayEnter()`

```php
public static function mayEnter($user, $level)
```

Whether a user may sign in: their permission level (Context::$levelAttribute) is at least Route::auth's 'level'

**Parameters**

+ `$user`
+ `$level`

Source: [framework/core/AuthRoutes.php:75](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L75)

<a name="authroutes-options"></a>
### `AuthRoutes::options()`

```php
public static function options(array $options)
```

The options with their defaults

**Parameters**

+ `$options` `array`

Source: [framework/core/AuthRoutes.php:90](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L90)

<a name="authroutes-register"></a>
### `AuthRoutes::register()`

```php
public static function register(array $options = array())
```

Registers the routes (Route::auth)

**Parameters**

+ `$options` `array`, default `array()`

Source: [framework/core/AuthRoutes.php:128](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L128)

<a name="authroutes-attempt"></a>
### `AuthRoutes::attempt()`

```php
public static function attempt(
    $username,
    $password,
    $ip,
    Throttle $throttle,
    callable $find,
    $level = 0,
    $perUser = 0
)
```

Checks a username and a password, with the failures counted per IP and username

**Parameters**

+ `$username` `string`: the value of the identifier (the username, the email address...)
+ `$password`
+ `$ip`
+ `$throttle` `Throttle`
+ `$find` `callable`: function (string $username): ?user (a model with verifyPassword())
+ `$level`, default `0`
+ `$perUser`, default `0`

**Returns** `array`: ['status' =&gt; 'ok', 'user' =&gt; $user] | ['status' =&gt; 'invalid'] | ['status' =&gt; 'locked']

Source: [framework/core/AuthRoutes.php:157](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L157)

<a name="authroutes-signin"></a>
### `AuthRoutes::signIn()`

```php
public static function signIn($user, ?callable $authorize = null, $how = null)
```

Signs a user in: a new session id (fixation), a new CSRF token, then Auth::authorize()

**Parameters**

+ `$user`
+ `$authorize` `?callable`, default `null`: replaces Auth::authorize (tests)
+ `$how`, default `null`

Source: [framework/core/AuthRoutes.php:190](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L190)

<a name="authroutes-remembersignin"></a>
### `AuthRoutes::rememberSignIn()`

```php
public static function rememberSignIn($how)
```

Records how this session signed in (2.21.3), for what only some sign-ins may do: 'password', 'passkey', 'face'...
signIn() does it with its third argument; a page that signs in with Auth::authorize() calls it itself.

**Parameters**

+ `$how`

Source: [framework/core/AuthRoutes.php:202](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L202)

<a name="authroutes-signedinby"></a>
### `AuthRoutes::signedInBy()`

```php
public static function signedInBy()
```

How this session signed in (2.21.3): 'password' or 'passkey' through Route::auth, what the application recorded
otherwise, null when nobody recorded it. A sign-in that does not prove a person (a face without a liveness check)
must not be able to change how the account signs in: check this first.

Source: [framework/core/AuthRoutes.php:216](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L216)

<a name="authroutes-signout"></a>
### `AuthRoutes::signOut()`

```php
public static function signOut(?callable $unauthorize = null)
```

Signs out: Auth::unauthorize(), a new session id and a new CSRF token

**Parameters**

+ `$unauthorize` `?callable`, default `null`

Source: [framework/core/AuthRoutes.php:224](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L224)

<a name="authroutes-regenerate"></a>
### `AuthRoutes::regenerate()`

```php
public static function regenerate()
```

session_regenerate_id(true) and a new CSRF token (self::$regenerate in tests)

Source: [framework/core/AuthRoutes.php:234](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L234)

<a name="authroutes-finder"></a>
### `AuthRoutes::finder()`

```php
public static function finder($model, $identifier = 'username')
```

How a user is found by the value people sign in with: findByUsername() for 'username' when the model has it,
else the model's findBy($column, $value), else a bound query of the query builder on the model's table

**Parameters**

+ `$model`
+ `$identifier`, default `'username'`

**Returns** `callable`: function (string $value): ?user

Source: [framework/core/AuthRoutes.php:249](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L249)

<a name="authroutes-registerinput"></a>
### `AuthRoutes::registerInput()`

```php
public static function registerInput($capability, array $parameters)
```

What the sign-up form sends to the register capability: every input its rules declare (the username and the
passcode when the capability is unknown)

**Parameters**

+ `$capability`
+ `$parameters` `array`

Source: [framework/core/AuthRoutes.php:268](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L268)

<a name="authroutes-registration"></a>
### `AuthRoutes::registration()`

```php
public static function registration(array $o, array $p, Context $context, $json = false)
```

What a sign-up leads to, without a request (signUp() answers it; tests)

**Parameters**

+ `$o` `array`: the options (options())
+ `$p` `array`: the parameters of the form
+ `$context` `Context`
+ `$json` `bool`, default `false`: a JSON request (its CSRF header is checked before)

**Returns** `array`: ['status' =&gt; int, 'json' =&gt; array] | ['view' =&gt; name, 'data' =&gt; array] | ['redirect' =&gt; path]

Source: [framework/core/AuthRoutes.php:291](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L291)

<a name="authroutes-ip"></a>
### `AuthRoutes::ip()`

```php
public static function ip()
```

The address of the request (REMOTE_ADDR: a forwarded header can be written by anyone)

Source: [framework/core/AuthRoutes.php:325](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L325)

<a name="authroutes-safereturn"></a>
### `AuthRoutes::safeReturn()`

```php
public static function safeReturn($return)
```

Whether ?return= of the sign-in page is a page of this site (2.20.0): a path, never another site

**Parameters**

+ `$return`

Source: [framework/core/AuthRoutes.php:335](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/AuthRoutes.php#L335)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Pages -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Controllers and views

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Rendering pages: the controller base class, the page controller of Route::page, views and design styles.

| Class | What it is |
|---|---|
| [`Caligrafy\Controller`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Controller#controller) | Parent Class that defines the properties and methods of a controller |
| [`Caligrafy\PageController`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Pages#pagecontroller) | Route::page('/books/{id}', 'Books/show', ['data' =&gt; ['book' =&gt; 'get_book']]) renders a view through this controller: 1. access: 'signedIn' =&gt; true sends visitors to /login; 'level' =&gt; N also sends people below level N to |
| [`Caligrafy\View`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Pages#view) | Class View is the view renderer of the application |
| [`Caligrafy\Designs`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Pages#designs) | A style is a DESIGN.md and the override stylesheet written from it, public/css/designs/&lt;name&gt;.css. |
| [`Caligrafy\HttpCache`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Pages#httpcache) | A capability declared with cache (#[Capability(..., readOnly: true, public: true, cache: 30)]) answered over REST, or a page declared with Route::page(..., ['cache' =&gt; 30]), is sent with Cache-Control: public, ... |

<a name="controller"></a>
## class Caligrafy\Controller

Parent Class that defines the properties and methods of a controller

Its 17 public methods have a page of their own: [Caligrafy\Controller](https://github.com/caligrafy/caligrafy-quill/wiki/API-Controller).

<a name="pagecontroller"></a>
## class Caligrafy\PageController

```php
namespace Caligrafy;

class PageController extends Controller
```

Source: [framework/core/PageController.php:25](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/PageController.php#L25)

Class PageController
Route::page('/books/{id}', 'Books/show', ['data' =&gt; ['book' =&gt; 'get_book']]) renders a view through this controller:
1. access: 'signedIn' =&gt; true sends visitors to /login; 'level' =&gt; N also sends people below level N to /notAuthorized (Auth::guard on Context::$levelAttribute)
2. data: each 'data' entry calls a read-only capability as the person who opens the page ($this-&gt;call(): the same rules as REST and MCP), with the query string and the route variables as inputs (the route variables win), or with the inputs it lists (['book' =&gt; ['get_book', ['id' =&gt; 3]]]). A refusal becomes the page's answer: a visitor is sent to sign in; otherwise 403 (error 1006) or 404 (error 1005), or the 'notFound' view (route variables, 'with', 'message', who opens it) with a 404 status
3. the view gets the route variables, 'with' values, the data, 'authorized' and 'user' (id, username, level) - never the query string
Pages never read models: capabilities do, so a page, REST and AI agents follow the same rules.

### Constants

+ `RESERVED = array('authorized', 'user')`

### Methods

+ [`->__construct()`](#pagecontroller-construct)
+ [`->render()`](#pagecontroller-render)
+ [`PageController::admit()`](#pagecontroller-admit)
+ [`PageController::identity()`](#pagecontroller-identity)
+ [`PageController::signInAddress()`](#pagecontroller-signinaddress)
+ [`PageController::routeVariables()`](#pagecontroller-routevariables)

<a name="pagecontroller-construct"></a>
#### `->__construct()`

```php
public function __construct()
```

Nothing to connect for a page without data: the controller is set up when a capability is called

Source: [framework/core/PageController.php:32](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/PageController.php#L32)

<a name="pagecontroller-render"></a>
#### `->render()`

```php
public function render($view, array $options = array())
```

**Parameters**

+ `$view` `string`: the view, as for view(): 'Books/show'
+ `$options` `array`, default `array()`: 'signedIn' (bool), 'level' (int), 'data' (array name =&gt; read-only capability or [capability, inputs]), 'with' (array of fixed view data), 'notFound' (a view for 404s); 2.20.0: 'visitorsOnly' (a path: signed-in people go there), 'comeBack' (bool: visitors come back here after signing in), 'query' (names of the query string the view gets, as strings, '' when absent); 2.26.0: 'cache' (seconds a visitor's copy may be shared, see HttpCache)

Source: [framework/core/PageController.php:44](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/PageController.php#L44)

<a name="pagecontroller-admit"></a>
#### `PageController::admit()`

```php
public static function admit(array $options, $label)
```

The access options of Route::page and Route::action: 'signedIn', 'level', 'comeBack', 'visitorsOnly'

**Parameters**

+ `$options` `array`
+ `$label`

**Returns** `bool`: true when the person was sent elsewhere

Source: [framework/core/PageController.php:107](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/PageController.php#L107)

<a name="pagecontroller-identity"></a>
#### `PageController::identity()`

```php
public static function identity()
```

Who opens the page: 'authorized' and 'user' (id, username, level), for every view the page controller renders

Source: [framework/core/PageController.php:132](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/PageController.php#L132)

<a name="pagecontroller-signinaddress"></a>
#### `PageController::signInAddress()`

```php
public static function signInAddress()
```

The sign-in page, with this page and its query string to come back to (2.20.0, 'comeBack'):
/login?return=/books/3%3Fpage%3D2. Route::auth goes back there after signing in.

Source: [framework/core/PageController.php:145](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/PageController.php#L145)

<a name="pagecontroller-routevariables"></a>
#### `PageController::routeVariables()`

```php
public static function routeVariables()
```

The variables of the route pattern only (/books/{id} -&gt; id), not the query string

Source: [framework/core/PageController.php:156](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/PageController.php#L156)

<a name="view"></a>
## class Caligrafy\View

```php
namespace Caligrafy;

class View extends \stdClass
```

Source: [framework/core/View.php:21](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/View.php#L21)

Class View is the view renderer of the application

### Public properties

+ `public $viewName`
+ `public $viewData`

### Methods

+ [`->__construct()`](#view-construct)
+ [`View::display()`](#view-display)
+ [`View::debug()`](#view-debug)
+ [`View::cache()`](#view-cache)
+ [`View::cacheFolder()`](#view-cachefolder)

<a name="view-construct"></a>
#### `->__construct()`

```php
public function __construct($viewName, $viewData = array())
```

_No doc comment._

**Parameters**

+ `$viewName`
+ `$viewData`, default `array()`

Source: [framework/core/View.php:28](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/View.php#L28)

<a name="view-display"></a>
#### `View::display()`

```php
public static function display($path, array $data = array())
```

Prints a Pug file (2.19.0). A view already compiled and up to date runs through Phug's Optimizer, which includes
the compiled PHP without building Phug's compiler (3 classes instead of about 100); a view to compile, or a
project that customized Phug at run time (its renderer already built), goes through Phug's renderer as before.

**Parameters**

+ `$path`
+ `$data` `array`, default `array()`

Source: [framework/core/View.php:49](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/View.php#L49)

<a name="view-debug"></a>
#### `View::debug()`

```php
public static function debug()
```

Phug's debug mode (line numbers of the Pug file in errors) only with APP_DEBUG=true: it makes every page about
three times slower (2.19.0)

Source: [framework/core/View.php:80](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/View.php#L80)

<a name="view-cache"></a>
#### `View::cache()`

```php
public static function cache()
```

Compiled templates are kept between requests: a view is compiled to PHP once, then again only when it or a file
it includes or extends changes. On by default; VIEW_CACHE=false compiles every view on every request. A project
that sets Phug's cache_dir itself keeps its own. Returns the folder used, or null (no cache). Also sets Phug's
debug mode from APP_DEBUG.

Source: [framework/core/View.php:91](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/View.php#L91)

<a name="view-cachefolder"></a>
#### `View::cacheFolder()`

```php
public static function cacheFolder()
```

A folder of the system's temporary directory for this project and this system user only (compiled templates are
PHP that runs): created private (0700), refused when someone else owns it or it cannot be written. Views compiled
in debug mode are kept apart (the cache does not know the options a view was compiled with).

Source: [framework/core/View.php:109](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/View.php#L109)

<a name="designs"></a>
## class Caligrafy\Designs

```php
namespace Caligrafy;

class Designs
```

Source: [framework/core/Designs.php:21](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Designs.php#L21)

Class Designs
A style is a DESIGN.md and the override stylesheet written from it, public/css/designs/&lt;name&gt;.css. DESIGN.md files
are looked up in this order, the first one wins on a name clash:

```
application/design/<name>/                the project's own styles
framework/design/local/<name>/            styles added to Caligrafy itself
framework/design/vendor/<vendor>/<name>/  collections copied from elsewhere (awesome-design-md...), by vendor name
```

The layout loads that stylesheet after the Caligrafy stylesheets when DESIGN_STYLE names it; an empty DESIGN_STYLE,
an unknown name or a style without its stylesheet keeps Caligrafy's own look.

### Constants

+ `VENDOR = 'framework/design/vendor'`
+ `LOCAL = 'framework/design/local'`
+ `APPLICATION = 'application/design'`
+ `STYLESHEETS = 'public/css/designs'`

### Methods

+ [`Designs::name()`](#designs-name)
+ [`Designs::setting()`](#designs-setting)
+ [`Designs::sources()`](#designs-sources)
+ [`Designs::all()`](#designs-all)
+ [`Designs::available()`](#designs-available)
+ [`Designs::source()`](#designs-source)
+ [`Designs::find()`](#designs-find)
+ [`Designs::stylesheet()`](#designs-stylesheet)
+ [`Designs::stylesheetUrl()`](#designs-stylesheeturl)
+ [`Designs::describe()`](#designs-describe)
+ [`Designs::status()`](#designs-status)
+ [`Designs::cli()`](#designs-cli)

<a name="designs-name"></a>
#### `Designs::name()`

```php
public static function name($value)
```

The style name of a value when it is a valid one (lowercase letters, digits, dot, dash, underscore), else ''

**Parameters**

+ `$value`

Source: [framework/core/Designs.php:31](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Designs.php#L31)

<a name="designs-setting"></a>
#### `Designs::setting()`

```php
public static function setting()
```

DESIGN_STYLE as loaded from .env (raw, trimmed): '' means Caligrafy's own look

Source: [framework/core/Designs.php:40](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Designs.php#L40)

<a name="designs-sources"></a>
#### `Designs::sources()`

```php
public static function sources($root = '.')
```

The folders that hold styles, first one wins: label =&gt; folder relative to the root

**Parameters**

+ `$root`, default `'.'`

Source: [framework/core/Designs.php:49](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Designs.php#L49)

<a name="designs-all"></a>
#### `Designs::all()`

```php
public static function all($name, $root = '.')
```

Every DESIGN.md of a name, in lookup order (the first one is used): label =&gt; path

**Parameters**

+ `$name`
+ `$root`, default `'.'`

Source: [framework/core/Designs.php:63](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Designs.php#L63)

<a name="designs-available"></a>
#### `Designs::available()`

```php
public static function available($root = '.')
```

The styles available, name =&gt; path of the DESIGN.md that is used (application, then local, then vendors)

**Parameters**

+ `$root`, default `'.'`

Source: [framework/core/Designs.php:78](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Designs.php#L78)

<a name="designs-source"></a>
#### `Designs::source()`

```php
public static function source($file, $root = '.')
```

Where a DESIGN.md comes from: application, local or vendor/&lt;vendor&gt;

**Parameters**

+ `$file`
+ `$root`, default `'.'`

Source: [framework/core/Designs.php:94](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Designs.php#L94)

<a name="designs-find"></a>
#### `Designs::find()`

```php
public static function find($name, $root = '.')
```

The DESIGN.md of a style, null when there is none

**Parameters**

+ `$name`
+ `$root`, default `'.'`

Source: [framework/core/Designs.php:105](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Designs.php#L105)

<a name="designs-stylesheet"></a>
#### `Designs::stylesheet()`

```php
public static function stylesheet($name, $root = '.')
```

Path of the override stylesheet of a style (it may not exist yet)

**Parameters**

+ `$name`
+ `$root`, default `'.'`

Source: [framework/core/Designs.php:114](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Designs.php#L114)

<a name="designs-stylesheeturl"></a>
#### `Designs::stylesheetUrl()`

```php
public static function stylesheetUrl($public, $root = '.')
```

URL of the stylesheet of the selected style, versioned by its modification time, or '' for Caligrafy's own look

**Parameters**

+ `$public`
+ `$root`, default `'.'`

Source: [framework/core/Designs.php:122](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Designs.php#L122)

<a name="designs-describe"></a>
#### `Designs::describe()`

```php
public static function describe($file, $max = 110)
```

One line describing a style: the description of its front matter, else its first paragraph

**Parameters**

+ `$file`
+ `$max`, default `110`

Source: [framework/core/Designs.php:133](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Designs.php#L133)

<a name="designs-status"></a>
#### `Designs::status()`

```php
public static function status($root = '.')
```

The state of the selected style, for doctor and design status

**Parameters**

+ `$root`, default `'.'`

**Returns** `array`: [status OK|WARN, message, fix]

Source: [framework/core/Designs.php:155](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Designs.php#L155)

<a name="designs-cli"></a>
#### `Designs::cli()`

```php
public static function cli(array $args, $root = '.', $envFile = '.env')
```

php caligrafer.php design list | show &lt;name&gt; | use &lt;name&gt; | off | status

**Parameters**

+ `$args` `array`
+ `$root`, default `'.'`
+ `$envFile`, default `'.env'`

**Returns** `int`: exit code

Source: [framework/core/Designs.php:183](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Designs.php#L183)

<a name="httpcache"></a>
## class Caligrafy\HttpCache

```php
namespace Caligrafy;

class HttpCache
```

Source: [framework/core/HttpCache.php:23](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/HttpCache.php#L23)

Class HttpCache
A capability declared with cache (#[Capability(..., readOnly: true, public: true, cache: 30)]) answered over REST, or
a page declared with Route::page(..., ['cache' =&gt; 30]), is sent with Cache-Control: public, max-age=30 when the
request is a GET or HEAD with no session cookie and no Authorization header: the production image's Apache cache
(docker/production/cache.conf), a CDN or a proxy then answer the next visitors from memory, without PHP.

Never kept: an answer to a signed-in person or a token (it is not marked), an answer that sets a cookie (a session
started while answering: a form's CSRF token) and any answer other than 200: guard() turns them into
Cache-Control: private, no-store just before the headers are sent. Vary: Cookie, Authorization keeps the copy for
visitors without them.

### Constants

+ `MAX = 86400`

### Methods

+ [`HttpCache::publicFor()`](#httpcache-publicfor)
+ [`HttpCache::shareable()`](#httpcache-shareable)
+ [`HttpCache::guard()`](#httpcache-guard)
+ [`HttpCache::reset()`](#httpcache-reset)

<a name="httpcache-publicfor"></a>
#### `HttpCache::publicFor()`

```php
public static function publicFor($seconds)
```

Marks the current answer public for $seconds when this request may share it

**Parameters**

+ `$seconds`

**Returns** `bool`: whether it was marked

Source: [framework/core/HttpCache.php:33](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/HttpCache.php#L33)

<a name="httpcache-shareable"></a>
#### `HttpCache::shareable()`

```php
public static function shareable()
```

Whether this request may receive a shared answer: GET or HEAD, no session cookie, no Authorization header

Source: [framework/core/HttpCache.php:52](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/HttpCache.php#L52)

<a name="httpcache-guard"></a>
#### `HttpCache::guard()`

```php
public static function guard()
```

Right before the headers go out: an answer that sets a cookie or is not a 200 is never kept

Source: [framework/core/HttpCache.php:67](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/HttpCache.php#L67)

<a name="httpcache-reset"></a>
#### `HttpCache::reset()`

```php
public static function reset()
```

For tests: forget that the header callback is registered

Source: [framework/core/HttpCache.php:86](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/HttpCache.php#L86)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Controller -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Caligrafy\Controller

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Part of [Controllers and views](https://github.com/caligrafy/caligrafy-quill/wiki/API-Pages).

<a name="controller"></a>
```php
namespace Caligrafy;

class Controller extends \stdClass
```

Source: [framework/core/Controller.php:19](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L19)

Parent Class that defines the properties and methods of a controller

## Methods

+ [`->__construct()`](#controller-construct)
+ [`->__invoke()`](#controller-invoke)
+ [`->activatePayment()`](#controller-activatepayment)
+ [`->associate()`](#controller-associate)
+ [`->index()`](#controller-index)
+ [`->all()`](#controller-all)
+ [`->find()`](#controller-find)
+ [`->save()`](#controller-save)
+ [`->delete()`](#controller-delete)
+ [`->search()`](#controller-search)
+ [`->table()`](#controller-table)
+ [`->check()`](#controller-check)
+ [`->validate()`](#controller-validate)
+ [`->filter()`](#controller-filter)
+ [`->view()`](#controller-view)
+ [`->api()`](#controller-api)
+ [`->call()`](#controller-call)

<a name="controller-construct"></a>
### `->__construct()`

```php
public function __construct($modelname = '', $table = null)
```

_No doc comment._

**Parameters**

+ `$modelname`, default `''`
+ `$table`, default `null`

Source: [framework/core/Controller.php:28](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L28)

<a name="controller-invoke"></a>
### `->__invoke()`

```php
public function __invoke($modelname, $table)
```

_No doc comment._

**Parameters**

+ `$modelname`
+ `$table`

Source: [framework/core/Controller.php:33](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L33)

<a name="controller-activatepayment"></a>
### `->activatePayment()`

```php
public function activatePayment()
```

Activates a the Stripe Payment module

Source: [framework/core/Controller.php:64](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L64)

<a name="controller-associate"></a>
### `->associate()`

```php
public function associate($modelname, $table)
```

Associates a controller with a model optionally with a table in the database

**Parameters**

+ `$modelname`
+ `$table`

Source: [framework/core/Controller.php:73](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L73)

<a name="controller-index"></a>
### `->index()`

```php
public function index()
```

Implied default function that will run when no action has been determined at runtime

Source: [framework/core/Controller.php:82](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L82)

<a name="controller-all"></a>
### `->all()`

```php
public function all($args = array())
```

Basic common CRUD function that fetches all data from the associated table

**Parameters**

+ `$args`, default `array()`

Source: [framework/core/Controller.php:88](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L88)

<a name="controller-find"></a>
### `->find()`

```php
public function find($id = null)
```

Basic common CRUD function that finds a particular record

**Parameters**

+ `$id`, default `null`

Source: [framework/core/Controller.php:96](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L96)

<a name="controller-save"></a>
### `->save()`

```php
public function save($inputs, $id = null)
```

Basic common CRUD function that saves data to the database whether adding a new record or updating an existing one

**Parameters**

+ `$inputs`
+ `$id`, default `null`

Source: [framework/core/Controller.php:104](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L104)

<a name="controller-delete"></a>
### `->delete()`

```php
public function delete($id = null)
```

Basic common CRUD function that deletes a record from the database

**Parameters**

+ `$id`, default `null`

Source: [framework/core/Controller.php:114](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L114)

<a name="controller-search"></a>
### `->search()`

```php
public function search($scope = null, $keywords = null)
```

_No doc comment._

**Parameters**

+ `$scope`, default `null`
+ `$keywords`, default `null`

Source: [framework/core/Controller.php:120](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L120)

<a name="controller-table"></a>
### `->table()`

```php
public function table()
```

Gets the table that is associated with a model

Source: [framework/core/Controller.php:131](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L131)

<a name="controller-check"></a>
### `->check()`

```php
public function check($data, $rules = array(), $filters = array())
```

Filtering and Validation through a controller

**Parameters**

+ `$data`
+ `$rules`, default `array()`
+ `$filters`, default `array()`

Source: [framework/core/Controller.php:139](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L139)

<a name="controller-validate"></a>
### `->validate()`

```php
public function validate($data, $rules)
```

Validation through a controller

**Parameters**

+ `$data`
+ `$rules`

Source: [framework/core/Controller.php:147](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L147)

<a name="controller-filter"></a>
### `->filter()`

```php
public function filter($data, $filters)
```

Filtering through a controller

**Parameters**

+ `$data`
+ `$filters`

Source: [framework/core/Controller.php:156](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L156)

<a name="controller-view"></a>
### `->view()`

```php
public function view($viewName, $viewData = array())
```

return a Pug template view with viewData passed to it

**Parameters**

+ `$viewName`
+ `$viewData`, default `array()`

Source: [framework/core/Controller.php:165](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L165)

<a name="controller-api"></a>
### `->api()`

```php
public function api($viewData = array())
```

return a view consumable by APIs

**Parameters**

+ `$viewData`, default `array()`

Source: [framework/core/Controller.php:173](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L173)

<a name="controller-call"></a>
### `->call()`

```php
public function call($name, $input = null)
```

Calls a capability as the signed-in user (web pages): the same rules as REST and MCP

```
try { $book = $this->call('create_book'); redirect('/books/' . $book['id']); }
catch (ServiceError $e) { return view('Books/form', ['errors' => $e->fields]); }
```

**Parameters**

+ `$name` `string`: the capability
+ `$input` `array|null`, default `null`: the inputs (default: the request parameters and the route variables)

**Returns** `mixed`: plain data

+ **@throws** ServiceError

Source: [framework/core/Controller.php:187](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Controller.php#L187)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Services and capabilities

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Build once: services, the capability registry, errors, the container, personal access tokens and the audit log.

| Class | What it is |
|---|---|
| [`Caligrafy\Service`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#service) | Extend it in application/services/, declare the inputs and implement handle() |
| [`Caligrafy\Capability`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capability) | #[Capability(name: 'create_book', description: 'Adds a book to the catalog', scope: 'books:write')] on a class that extends Caligrafy\Service. |
| [`Caligrafy\Capabilities`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capabilities) | A capability is a class of application/services/ that extends Service and carries #[Capability(...)]. |
| [`Caligrafy\ServiceError`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#serviceerror) | A service throws it to refuse a call. |
| [`Caligrafy\Container`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#container) | Capabilities are made by the container, so a service asks for what it uses in its constructor |
| [`Caligrafy\Tokens`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#tokens) | A token is `cq_<id>_<secret>`: shown once when it is created, stored only as a SHA-256 hash in caligrafy_tokens with a name, an optional owner (users.id), its scopes, an optional expiry, the last use and a revocation ... |
| [`Caligrafy\Audit`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#audit) | One row per capability call that changes data, and per refused call: when, who (a user, a token, the CLI), through which channel, which capability and the outcome. |

<a name="service"></a>
## abstract class Caligrafy\Service

```php
namespace Caligrafy;

abstract class Service
```

Source: [framework/core/Service.php:34](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Service.php#L34)

Class Service
Extend it in application/services/, declare the inputs and implement handle():

```
#[Capability(name: 'create_book', description: 'Adds a book', scope: 'books:write')]
class CreateBook extends Service {
    public $rules = ['title' => 'required|max_len,255', 'author_id' => 'required|integer'];
    public $filters = ['title' => 'trim|sanitize_string'];
    public $descriptions = ['title' => 'The title of the book'];
    public function handle(array $input, Context $context) {
        return (new Book('books'))->create($input);
    }
}
```

- $rules: GUMP validation rules per input. Only the inputs listed here reach handle(); use '' for an input without a rule. They also give the JSON Schema that agents and clients see (Capabilities::schema()). A file input takes the rule 'file' (2.19.0): 'cover' =&gt; 'required|file|extension,png;jpg|max_size,2mb'. Web pages and REST save the uploaded file and give handle() its public URL; MCP and the command line send a URL or a path (Caligrafy\Uploads).
- $filters: GUMP filters applied before validation.
- handle() returns data (an array, a model, a list of models, a scalar) and throws ServiceError to refuse. It never renders a view, redirects, prints or reads the request or the session: the context says who calls.

### Public properties

+ `public $rules = array()`: array input =&gt; GUMP rules
+ `public $filters = array()`: array input =&gt; GUMP filters
+ `public $descriptions = array()`: array input =&gt; description, for the schema

### Methods

+ [`->handle()`](#service-handle)
+ [`->validate()`](#service-validate)
+ [`->capability()`](#service-capability)
+ [`->run()`](#service-run)

<a name="service-handle"></a>
#### `->handle()`

```php
abstract public function handle(array $input, Context $context)
```

Does the work

**Parameters**

+ `$input` `array`: the validated and filtered inputs (only those of $rules)
+ `$context` `Context`: who calls, through which channel

**Returns** `mixed`: the result

Source: [framework/core/Service.php:51](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Service.php#L51)

<a name="service-validate"></a>
#### `->validate()`

```php
public function validate(array $input)
```

Keeps the declared inputs, filters them and validates them

**Parameters**

+ `$input` `array`

**Returns** `array`: the clean inputs

+ **@throws** ServiceError invalid, with a message per field

Source: [framework/core/Service.php:58](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Service.php#L58)

<a name="service-capability"></a>
#### `->capability()`

```php
protected function capability($name, array $input, Context $context)
```

Calls another capability as the same person (2.21.0)

**Parameters**

+ `$name`
+ `$input` `array`
+ `$context` `Context`

Source: [framework/core/Service.php:99](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Service.php#L99)

<a name="service-run"></a>
#### `->run()`

```php
public function run(array $input, ?Context $context = null)
```

_No doc comment._

**Parameters**

+ `$input` `array`
+ `$context` `?Context`, default `null`

Source: [framework/core/Service.php:104](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Service.php#L104)

<a name="capability"></a>
## class Caligrafy\Capability

```php
namespace Caligrafy;

class Capability
```

Source: [framework/core/Capability.php:17](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Capability.php#L17)

Attribute Capability
#[Capability(name: 'create_book', description: 'Adds a book to the catalog', scope: 'books:write')]
on a class that extends Caligrafy\Service. Its name is how REST, MCP, the JS client and the CLI call it.

### Methods

+ [`->__construct()`](#capability-construct)

<a name="capability-construct"></a>
#### `->__construct()`

```php
public function __construct(
    public string $name,
    public string $description = '',
    public string $scope = '',
    public int $level = 0,
    public bool $readOnly = false,
    public bool $destructive = false,
    public bool $public = false,
    public bool $mcp = true,
    public bool $webOnly = false,
    public bool $async = false,
    public int $cache = 0
)
```

**Parameters**

+ `$name` `string`: snake_case, unique in the application (create_book)
+ `$description` `string`, default `''`: one or two sentences: what it does and returns (shown to agents as the tool description)
+ `$scope` `string`, default `''`: the token scope it needs (books:write); '' = none for a read-only one, its own name for a write one (2.26.0: a token needs the scope create_book, or \*; TOKEN_DEFAULT_SCOPES=false, deprecated: none)
+ `$level` `int`, default `0`: the minimum value of the users permission column (0 = any signed-in user)
+ `$readOnly` `bool`, default `false`: true when it changes nothing (not audited when it succeeds; agents may call it freely)
+ `$destructive` `bool`, default `false`: true when it deletes or overwrites data (agents ask before calling it)
+ `$public` `bool`, default `false`: true when anyone may call it without signing in or a token
+ `$mcp` `bool`, default `true`: false keeps it out of the MCP tools (one only a browser can use, such as a push subscription)
+ `$webOnly` `bool`, default `false`: true (2.21.0): only Route::action() reaches it: it may read the session and sign people in
+ `$async` `bool`, default `false`: true (2.23.0): Snap cards run it in the background as a task; REST, MCP, pages and call run it directly
+ `$cache` `int`, default `0`: seconds (2.26.0): a GET of it over REST by a visitor with no session cookie and no token may be kept by shared caches (the production image's own cache, a CDN) for that long; needs readOnly and public, and an answer that is the same for every visitor

Source: [framework/core/Capability.php:35](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Capability.php#L35)

<a name="capabilities"></a>
## class Caligrafy\Capabilities

```php
namespace Caligrafy;

class Capabilities
```

Source: [framework/core/Capabilities.php:23](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Capabilities.php#L23)

Class Capabilities
A capability is a class of application/services/ that extends Service and carries #[Capability(...)].
Every channel calls it through call(), which always does the same, in order:
1. finds it (not_found)
2. checks the context: public, or signed in / a token (unauthenticated), with the scope and level (forbidden); a token needs the declared scope, or for a write capability that declares none its own name (scopeOf(), 2.26.0)
3. keeps, filters and validates the declared inputs (invalid)
4. runs handle()
5. writes the audit log: every refusal, and every success of a capability that is not read-only
and returns plain data (models become arrays of their columns).

### Public properties

+ `public static $defaultScopes = null`: bool|null whether a write capability declared without a scope needs the scope named after it from a token (2.26.0): null until the first use reads TOKEN_DEFAULT_SCOPES (false, deprecated: any token, as before)

### Methods

+ [`Capabilities::scopeOf()`](#capabilities-scopeof)
+ [`Capabilities::unscopedWrites()`](#capabilities-unscopedwrites)
+ [`Capabilities::register()`](#capabilities-register)
+ [`Capabilities::all()`](#capabilities-all)
+ [`Capabilities::get()`](#capabilities-get)
+ [`Capabilities::available()`](#capabilities-available)
+ [`Capabilities::call()`](#capabilities-call)
+ [`Capabilities::schema()`](#capabilities-schema)
+ [`Capabilities::schemaFromRules()`](#capabilities-schemafromrules)
+ [`Capabilities::describe()`](#capabilities-describe)
+ [`Capabilities::plain()`](#capabilities-plain)
+ [`Capabilities::reset()`](#capabilities-reset)

<a name="capabilities-scopeof"></a>
#### `Capabilities::scopeOf()`

```php
public static function scopeOf(Capability $capability)
```

The scope a token needs to call a capability (2.26.0): the one it declares; for a write capability (not readOnly,
not public) declared without one, its own name (create_book), which a token grants by that name or by \*.
Read-only and public capabilities without a scope need none. Signed-in users and the CLI never need a scope.

**Parameters**

+ `$capability` `Capability`

Source: [framework/core/Capabilities.php:42](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Capabilities.php#L42)

<a name="capabilities-unscopedwrites"></a>
#### `Capabilities::unscopedWrites()`

```php
public static function unscopedWrites()
```

The write capabilities declared without a scope, each with the scope a token now needs to call them (doctor)

**Returns** `array`: name =&gt; scope

Source: [framework/core/Capabilities.php:60](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Capabilities.php#L60)

<a name="capabilities-register"></a>
#### `Capabilities::register()`

```php
public static function register($class)
```

Registers a service class that is not in application/services/

**Parameters**

+ `$class`

Source: [framework/core/Capabilities.php:75](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Capabilities.php#L75)

<a name="capabilities-all"></a>
#### `Capabilities::all()`

```php
public static function all()
```

Every capability, by name

**Returns** `array`: name =&gt; ['class' =&gt; string, 'capability' =&gt; Capability]

Source: [framework/core/Capabilities.php:85](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Capabilities.php#L85)

<a name="capabilities-get"></a>
#### `Capabilities::get()`

```php
public static function get($name)
```

One capability (null when there is none of that name)

**Parameters**

+ `$name`

Source: [framework/core/Capabilities.php:119](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Capabilities.php#L119)

<a name="capabilities-available"></a>
#### `Capabilities::available()`

```php
public static function available(Context $context)
```

The capabilities a context may call (MCP lists only these)

**Parameters**

+ `$context` `Context`

Source: [framework/core/Capabilities.php:127](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Capabilities.php#L127)

<a name="capabilities-call"></a>
#### `Capabilities::call()`

```php
public static function call($name, array $input, Context $context, ?Uploads $uploads = null)
```

Calls a capability

**Parameters**

+ `$name` `string`: the capability name
+ `$input` `array`: the inputs (extra keys are ignored)
+ `$context` `Context`: who calls, through which channel
+ `$uploads` `?Uploads`, default `null`: the files of the request (web and REST): saved once the caller is allowed, given to the capability as their URLs, deleted again when the call fails

**Returns** `mixed`: plain data

+ **@throws** ServiceError

Source: [framework/core/Capabilities.php:145](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Capabilities.php#L145)

<a name="capabilities-schema"></a>
#### `Capabilities::schema()`

```php
public static function schema($name)
```

The JSON Schema of a capability's inputs, from its GUMP rules

**Parameters**

+ `$name`

Source: [framework/core/Capabilities.php:195](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Capabilities.php#L195)

<a name="capabilities-schemafromrules"></a>
#### `Capabilities::schemaFromRules()`

```php
public static function schemaFromRules(array $rules, array $descriptions = array())
```

JSON Schema (draft 2020-12 subset) of GUMP rules

**Parameters**

+ `$rules` `array`: input =&gt; 'required|max_len,100|integer'
+ `$descriptions` `array`, default `array()`: input =&gt; description

Source: [framework/core/Capabilities.php:210](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Capabilities.php#L210)

<a name="capabilities-describe"></a>
#### `Capabilities::describe()`

```php
public static function describe(?Context $context = null)
```

The description of every capability, as a list (php caligrafer.php capabilities, the REST listing)

**Parameters**

+ `$context` `?Context`, default `null`: only the capabilities this context may call

Source: [framework/core/Capabilities.php:273](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Capabilities.php#L273)

<a name="capabilities-plain"></a>
#### `Capabilities::plain()`

```php
public static function plain($value)
```

Plain data: models become arrays of their public columns, recursively

**Parameters**

+ `$value`

Source: [framework/core/Capabilities.php:291](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Capabilities.php#L291)

<a name="capabilities-reset"></a>
#### `Capabilities::reset()`

```php
public static function reset()
```

Forgets the registry (tests)

Source: [framework/core/Capabilities.php:350](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Capabilities.php#L350)

<a name="serviceerror"></a>
## class Caligrafy\ServiceError

```php
namespace Caligrafy;

class ServiceError extends \Exception
```

Source: [framework/core/ServiceError.php:16](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ServiceError.php#L16)

Class ServiceError
A service throws it to refuse a call. Each channel turns it into its own form: an HTTP status and a JSON error for
REST, a tool error for MCP, the errors of a form for web pages.

### Constants

+ `STATUSES = array('invalid' => 422, 'unauthenticated' => 401, 'forbidden' => 403, 'not_found' => 404, 'conflict' => 409)`

### Public properties

+ `public $kind`: string invalid, unauthenticated, forbidden, not_found or conflict
+ `public $fields`: array field =&gt; message, for invalid input

### Methods

+ [`->__construct()`](#serviceerror-construct)
+ [`ServiceError::invalid()`](#serviceerror-invalid)
+ [`ServiceError::unauthenticated()`](#serviceerror-unauthenticated)
+ [`ServiceError::forbidden()`](#serviceerror-forbidden)
+ [`ServiceError::notFound()`](#serviceerror-notfound)
+ [`ServiceError::conflict()`](#serviceerror-conflict)
+ [`->status()`](#serviceerror-status)
+ [`->toArray()`](#serviceerror-toarray)

<a name="serviceerror-construct"></a>
#### `->__construct()`

```php
public function __construct($kind, $message = '', array $fields = array())
```

_No doc comment._

**Parameters**

+ `$kind`
+ `$message`, default `''`
+ `$fields` `array`, default `array()`

Source: [framework/core/ServiceError.php:26](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ServiceError.php#L26)

<a name="serviceerror-invalid"></a>
#### `ServiceError::invalid()`

```php
public static function invalid(array $fields, $message = 'Some of the inputs are invalid')
```

_No doc comment._

**Parameters**

+ `$fields` `array`
+ `$message`, default `'Some of the inputs are invalid'`

Source: [framework/core/ServiceError.php:36](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ServiceError.php#L36)

<a name="serviceerror-unauthenticated"></a>
#### `ServiceError::unauthenticated()`

```php
public static function unauthenticated($message = 'Sign in or send a personal access token')
```

_No doc comment._

**Parameters**

+ `$message`, default `'Sign in or send a personal access token'`

Source: [framework/core/ServiceError.php:41](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ServiceError.php#L41)

<a name="serviceerror-forbidden"></a>
#### `ServiceError::forbidden()`

```php
public static function forbidden($message = 'You are not allowed to do this')
```

_No doc comment._

**Parameters**

+ `$message`, default `'You are not allowed to do this'`

Source: [framework/core/ServiceError.php:46](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ServiceError.php#L46)

<a name="serviceerror-notfound"></a>
#### `ServiceError::notFound()`

```php
public static function notFound($message = 'Not found')
```

_No doc comment._

**Parameters**

+ `$message`, default `'Not found'`

Source: [framework/core/ServiceError.php:51](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ServiceError.php#L51)

<a name="serviceerror-conflict"></a>
#### `ServiceError::conflict()`

```php
public static function conflict($message)
```

_No doc comment._

**Parameters**

+ `$message`

Source: [framework/core/ServiceError.php:56](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ServiceError.php#L56)

<a name="serviceerror-status"></a>
#### `->status()`

```php
public function status()
```

The HTTP status of this error

Source: [framework/core/ServiceError.php:64](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ServiceError.php#L64)

<a name="serviceerror-toarray"></a>
#### `->toArray()`

```php
public function toArray()
```

{"error": {"code": "invalid", "message": "...", "fields": {...}}}

Source: [framework/core/ServiceError.php:72](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ServiceError.php#L72)

<a name="container"></a>
## class Caligrafy\Container

```php
namespace Caligrafy;

class Container
```

Source: [framework/core/Container.php:25](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Container.php#L25)

Class Container (2.18.0)
Capabilities are made by the container, so a service asks for what it uses in its constructor:

```
public function __construct(private Mailer $mailer) {}
```

A class the container has no binding for is built with its constructor's parameters resolved the same way (a class
or interface type -&gt; Container::get, else the parameter's default). Bindings go in application/config/container.php:

```
Container::singleton(PaymentGateway::class, fn () => new StripeGateway(getenv('STRIPE_SECRET')));
Container::bind(Clock::class, SystemClock::class);
```

A test swaps one with Container::instance(Mailer::class, $fake), then Container::reset() forgets it.

### Constants

+ `FILE = 'config/container.php'`

### Methods

+ [`Container::bind()`](#container-bind)
+ [`Container::singleton()`](#container-singleton)
+ [`Container::instance()`](#container-instance)
+ [`Container::has()`](#container-has)
+ [`Container::get()`](#container-get)
+ [`Container::make()`](#container-make)
+ [`Container::boot()`](#container-boot)
+ [`Container::forgetInstances()`](#container-forgetinstances)
+ [`Container::keepInstances()`](#container-keepinstances)
+ [`Container::reset()`](#container-reset)

<a name="container-bind"></a>
#### `Container::bind()`

```php
public static function bind($id, $factory = null)
```

A new object each time: $factory is a callable returning it, or a class name (an interface bound to a class)

**Parameters**

+ `$id`
+ `$factory`, default `null`

Source: [framework/core/Container.php:38](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Container.php#L38)

<a name="container-singleton"></a>
#### `Container::singleton()`

```php
public static function singleton($id, $factory = null)
```

One object for the whole request, made the first time it is asked for

**Parameters**

+ `$id`
+ `$factory`, default `null`

Source: [framework/core/Container.php:46](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Container.php#L46)

<a name="container-instance"></a>
#### `Container::instance()`

```php
public static function instance($id, $object)
```

This object for $id (a test's fake, for example)

**Parameters**

+ `$id`
+ `$object`

Source: [framework/core/Container.php:54](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Container.php#L54)

<a name="container-has"></a>
#### `Container::has()`

```php
public static function has($id)
```

Whether $id has a binding or an instance

**Parameters**

+ `$id`

Source: [framework/core/Container.php:64](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Container.php#L64)

<a name="container-get"></a>
#### `Container::get()`

```php
public static function get($id)
```

The object for $id: its instance, its binding, or the class built with its dependencies

**Parameters**

+ `$id`

Source: [framework/core/Container.php:73](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Container.php#L73)

<a name="container-make"></a>
#### `Container::make()`

```php
public static function make($class, array $parameters = array())
```

Builds $class (never a shared instance): the constructor parameters named in $parameters, then by type, then
their defaults

**Parameters**

+ `$class`
+ `$parameters` `array`, default `array()`

Source: [framework/core/Container.php:96](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Container.php#L96)

<a name="container-boot"></a>
#### `Container::boot()`

```php
public static function boot()
```

Loads application/config/container.php once (the web front controller does it after config.php; the CLI and
tests the first time the container is used)

Source: [framework/core/Container.php:132](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Container.php#L132)

<a name="container-forgetinstances"></a>
#### `Container::forgetInstances()`

```php
public static function forgetInstances()
```

Forgets the objects made so far, keeping the bindings (2.26.0: between two requests of the async server, so no
shared instance carries one caller's state to the next)

Source: [framework/core/Container.php:147](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Container.php#L147)

<a name="container-keepinstances"></a>
#### `Container::keepInstances()`

```php
public static function keepInstances()
```

Keeps the instances made so far (the ones application/config/container.php registered at boot): forgetInstances()
goes back to them

Source: [framework/core/Container.php:157](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Container.php#L157)

<a name="container-reset"></a>
#### `Container::reset()`

```php
public static function reset()
```

Forgets every binding and instance (tests); the bindings file is read again on next use

Source: [framework/core/Container.php:165](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Container.php#L165)

<a name="tokens"></a>
## class Caligrafy\Tokens

```php
namespace Caligrafy;

class Tokens
```

Source: [framework/core/Tokens.php:20](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Tokens.php#L20)

Class Tokens
A token is `cq_<id>_<secret>`: shown once when it is created, stored only as a SHA-256 hash in caligrafy_tokens
with a name, an optional owner (users.id), its scopes, an optional expiry, the last use and a revocation date.

Scopes are `<resource>:<action>` strings (books:read, books:write). A token scope `*` grants everything and
`books:*` grants every action on books. A capability's own name (create_book) is a scope too (2.26.0): the one a write
capability declared without a scope needs (Capabilities::scopeOf()). Tables: framework/settings/platform.sql (php caligrafer.php platform install).

### Constants

+ `TABLE = 'caligrafy_tokens'`
+ `PREFIX = 'cq_'`

### Methods

+ [`Tokens::create()`](#tokens-create)
+ [`Tokens::verify()`](#tokens-verify)
+ [`Tokens::expired()`](#tokens-expired)
+ [`Tokens::expiresAt()`](#tokens-expiresat)
+ [`Tokens::revoke()`](#tokens-revoke)
+ [`Tokens::all()`](#tokens-all)
+ [`Tokens::installed()`](#tokens-installed)
+ [`Tokens::looksLikeToken()`](#tokens-looksliketoken)
+ [`Tokens::parse()`](#tokens-parse)
+ [`Tokens::allows()`](#tokens-allows)
+ [`Tokens::normalizeScopes()`](#tokens-normalizescopes)

<a name="tokens-create"></a>
#### `Tokens::create()`

```php
public static function create($name, $scopes = array(), $userId = null, $expiresAt = null)
```

Creates a token

**Parameters**

+ `$name` `string`: what the token is for ("Claude Code on my laptop")
+ `$scopes` `array`, default `array()`: the scopes it grants
+ `$userId` `int|null`, default `null`: the user it acts for (null: the application itself)
+ `$expiresAt` `int|string|null`, default `null`: a Unix time (time() + 86400 * 90), or a local 'Y-m-d H:i:s' (null: never expires)

**Returns** `array`: ['id' =&gt; ..., 'token' =&gt; 'cq_...']: the token is never shown again

Source: [framework/core/Tokens.php:33](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Tokens.php#L33)

<a name="tokens-verify"></a>
#### `Tokens::verify()`

```php
public static function verify($token)
```

Checks a token and records its use

**Parameters**

+ `$token` `string`: the token as sent (Authorization: Bearer cq_...)

**Returns** `array|null`: the token row (id, name, scopes as an array, user_id...) or null when unknown, revoked or expired

Source: [framework/core/Tokens.php:54](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Tokens.php#L54)

<a name="tokens-expired"></a>
#### `Tokens::expired()`

```php
public static function expired($expiresAt, $now = null)
```

Whether an expiry date (local 'Y-m-d H:i:s', SERVER_TIMEZONE) has passed

**Parameters**

+ `$expiresAt` `string|null`: the expires_at column (null: never expires)
+ `$now` `int|null`, default `null`: a Unix time (null: now)

Source: [framework/core/Tokens.php:79](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Tokens.php#L79)

<a name="tokens-expiresat"></a>
#### `Tokens::expiresAt()`

```php
public static function expiresAt($expiresAt)
```

The expires_at value of an expiry given as a Unix time. Dates are stored in local time (SERVER_TIMEZONE), and when
the clocks fall back the repeated hour names two instants: strtotime() reads its first one. A token created at
01:21 EDT to expire an hour later (01:21 EST) would be refused at once, so an instant of the second occurrence
is stored as the first local time after the repeated hour (02:00): it never stops early, at worst an hour late.

**Parameters**

+ `$expiresAt` `int|string|null`: a Unix time, a local 'Y-m-d H:i:s' (kept as given) or null (never expires)

**Returns** `string|null`

Source: [framework/core/Tokens.php:96](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Tokens.php#L96)

<a name="tokens-revoke"></a>
#### `Tokens::revoke()`

```php
public static function revoke($id)
```

Revokes a token

**Parameters**

+ `$id`

**Returns** `bool`: true when a token was revoked

Source: [framework/core/Tokens.php:112](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Tokens.php#L112)

<a name="tokens-all"></a>
#### `Tokens::all()`

```php
public static function all()
```

Lists the tokens (never their secret)

**Returns** `array`: rows, newest first

Source: [framework/core/Tokens.php:126](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Tokens.php#L126)

<a name="tokens-installed"></a>
#### `Tokens::installed()`

```php
public static function installed()
```

Whether the framework tables exist (php caligrafer.php platform install)

Source: [framework/core/Tokens.php:139](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Tokens.php#L139)

<a name="tokens-looksliketoken"></a>
#### `Tokens::looksLikeToken()`

```php
public static function looksLikeToken($token)
```

Whether a request carries a token of this format (as opposed to a legacy API key)

**Parameters**

+ `$token`

Source: [framework/core/Tokens.php:152](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Tokens.php#L152)

<a name="tokens-parse"></a>
#### `Tokens::parse()`

```php
public static function parse($token)
```

The id of a well-formed token, null otherwise

**Parameters**

+ `$token`

Source: [framework/core/Tokens.php:160](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Tokens.php#L160)

<a name="tokens-allows"></a>
#### `Tokens::allows()`

```php
public static function allows($granted, $required)
```

Whether granted scopes cover a required scope: exact, `<resource>:*` or `*`. An empty requirement is always met.

**Parameters**

+ `$granted`
+ `$required`

Source: [framework/core/Tokens.php:168](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Tokens.php#L168)

<a name="tokens-normalizescopes"></a>
#### `Tokens::normalizeScopes()`

```php
public static function normalizeScopes($scopes)
```

Scopes as a sorted list of unique, valid strings (from an array or a space/comma separated string)

**Parameters**

+ `$scopes`

Source: [framework/core/Tokens.php:188](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Tokens.php#L188)

<a name="audit"></a>
## class Caligrafy\Audit

```php
namespace Caligrafy;

class Audit
```

Source: [framework/core/Audit.php:17](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Audit.php#L17)

Class Audit
One row per capability call that changes data, and per refused call: when, who (a user, a token, the CLI),
through which channel, which capability and the outcome. Inputs are never stored.
Without the table (php caligrafer.php platform install) nothing is written and nothing fails.

### Constants

+ `TABLE = 'caligrafy_audit'`

### Methods

+ [`Audit::record()`](#audit-record)
+ [`Audit::latest()`](#audit-latest)

<a name="audit-record"></a>
#### `Audit::record()`

```php
public static function record(Context $context, $capability, $outcome, $detail = null)
```

Records one call

**Parameters**

+ `$context` `Context`: who called and through which channel
+ `$capability` `string`: the capability name
+ `$outcome` `string`: ok, invalid, unauthenticated, forbidden, not_found, conflict, error
+ `$detail` `string|null`, default `null`: a short note (an error message), at most 500 characters

**Returns** `bool`: whether the row was written

Source: [framework/core/Audit.php:29](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Audit.php#L29)

<a name="audit-latest"></a>
#### `Audit::latest()`

```php
public static function latest($limit = 50, $capability = null)
```

The latest rows, newest first

**Parameters**

+ `$limit` `int`, default `50`: how many
+ `$capability` `string|null`, default `null`: only this capability

Source: [framework/core/Audit.php:46](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Audit.php#L46)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Data -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Data

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Models, the query builder, the database connection, migrations, validation and the cache.

| Class | What it is |
|---|---|
| [`Caligrafy\Model`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Model#model) | Class Model is the base model from which the application models can be extended |
| [`Caligrafy\Query`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query#query) | Builds one SQL statement with bound values only. |
| [`Caligrafy\Database`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Database#database) | The Database class handles all database connections and global functions that interface directly with the database |
| [`Caligrafy\Migrations`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data#migrations) | application/migrations/&lt;number&gt;_&lt;name&gt;.sql: php caligrafer.php migrate runs, in number order, the files that never ran on this database, and records each one in caligrafy_migrations (its name, its sha256, when). |
| [`Caligrafy\Validator`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data#validator) | Class that validates inputs |
| [`Caligrafy\Cache`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data#cache) | CACHE_STORE in .env: database (the default with DB_ACTIVATE=true: the caligrafy_cache table, which the deploy step and php caligrafer.php platform install create, shared by the web server, the queue, scheduled jobs and ... |
| [`Caligrafy\Lazy`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data#lazy) | #[Caligrafy\Lazy] on a relation method of a model (2.26.0): it may load lazily, without [ERROR 2004] or a warning |
| [`Caligrafy\LazyLoadingException`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data#lazyloadingexception) | Thrown in development when a relation loads lazily on one of several models a query read ([ERROR 2004], 2.26.0) |

<a name="model"></a>
## class Caligrafy\Model

Class Model is the base model from which the application models can be extended

Its 24 public methods have a page of their own: [Caligrafy\Model](https://github.com/caligrafy/caligrafy-quill/wiki/API-Model).

<a name="query"></a>
## class Caligrafy\Query

Builds one SQL statement with bound values only.

Its 47 public methods have a page of their own: [Caligrafy\Query](https://github.com/caligrafy/caligrafy-quill/wiki/API-Query).

<a name="database"></a>
## class Caligrafy\Database

The Database class handles all database connections and global functions that interface directly with the database

Its 16 public methods have a page of their own: [Caligrafy\Database](https://github.com/caligrafy/caligrafy-quill/wiki/API-Database).

<a name="migrations"></a>
## class Caligrafy\Migrations

```php
namespace Caligrafy;

class Migrations
```

Source: [framework/core/Migrations.php:23](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Migrations.php#L23)

Class Migrations
application/migrations/&lt;number&gt;_&lt;name&gt;.sql: php caligrafer.php migrate runs, in number order, the files that never
ran on this database, and records each one in caligrafy_migrations (its name, its sha256, when). A file is never run
twice: change the database with a new file, not by editing one that ran (status shows it as "changed", and deploy
warns). The deploy step (php caligrafer.php deploy) runs them after the create_db.sql scripts. Forward only: undo a
change with a new migration.

The statements of a file are split on ; outside quotes and comments. A file stops at its first failing statement:
it is not recorded, the statements before it stay applied (MySQL commits a CREATE or ALTER at once), so write each
file so that it can run again (IF NOT EXISTS), or keep one change per file.

### Constants

+ `FOLDER = 'application/migrations'`
+ `TABLE = 'caligrafy_migrations'`
+ `PATTERN = '/^(\d{1,14})_([A-Za-z0-9_]+)\.sql$/'`

### Methods

+ [`->__construct()`](#migrations-construct)
+ [`->files()`](#migrations-files)
+ [`Migrations::install()`](#migrations-install)
+ [`->status()`](#migrations-status)
+ [`->run()`](#migrations-run)
+ [`->make()`](#migrations-make)
+ [`Migrations::statements()`](#migrations-statements)

<a name="migrations-construct"></a>
#### `->__construct()`

```php
public function __construct($root = '.')
```

_No doc comment._

**Parameters**

+ `$root`, default `'.'`

Source: [framework/core/Migrations.php:31](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Migrations.php#L31)

<a name="migrations-files"></a>
#### `->files()`

```php
public function files()
```

The migration files, in order: name =&gt; path (relative to the project)

Source: [framework/core/Migrations.php:39](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Migrations.php#L39)

<a name="migrations-install"></a>
#### `Migrations::install()`

```php
public static function install()
```

Creates the table that records the migrations that ran

Source: [framework/core/Migrations.php:65](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Migrations.php#L65)

<a name="migrations-status"></a>
#### `->status()`

```php
public function status()
```

Every migration with its state: ran, pending, or changed (it ran, then its file was edited)

**Returns** `array`: of ['name', 'path', 'state', 'ran_at']

Source: [framework/core/Migrations.php:75](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Migrations.php#L75)

<a name="migrations-run"></a>
#### `->run()`

```php
public function run(?callable $say = null)
```

Runs the pending migrations, in order; stops at the first that fails (the exception names it)

**Parameters**

+ `$say` `?callable`, default `null`

**Returns** `array`: the names that ran

Source: [framework/core/Migrations.php:95](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Migrations.php#L95)

<a name="migrations-make"></a>
#### `->make()`

```php
public function make($name, $at = null)
```

Writes a new, empty migration: application/migrations/&lt;YYYYMMDDHHMMSS&gt;_&lt;name&gt;.sql

**Parameters**

+ `$name`
+ `$at`, default `null`

**Returns** `string`: its path

Source: [framework/core/Migrations.php:125](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Migrations.php#L125)

<a name="migrations-statements"></a>
#### `Migrations::statements()`

```php
public static function statements($sql)
```

The statements of a SQL script: split on ; outside quotes ('...', "...", `...`) and comments (--, #, /* \*\/),
comments removed, empty statements dropped

**Parameters**

+ `$sql`

Source: [framework/core/Migrations.php:147](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Migrations.php#L147)

<a name="validator"></a>
## class Caligrafy\Validator

```php
namespace Caligrafy;

class Validator extends \GUMP
```

Source: [framework/core/Validator.php:29](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Validator.php#L29)

Class that validates inputs

### Constants

+ `MESSAGES = array('exists' => 'There is no such {param}', 'unique' => 'This {param} is already used')`

### Methods

+ [`->__construct()`](#validator-construct)
+ [`Validator::registerRules()`](#validator-registerrules)
+ [`Validator::exists()`](#validator-exists)
+ [`Validator::unique()`](#validator-unique)
+ [`Validator::normalize()`](#validator-normalize)
+ [`->validate()`](#validator-validate)
+ [`->get_errors_array()`](#validator-get-errors-array)
+ [`->check()`](#validator-check)

<a name="validator-construct"></a>
#### `->__construct()`

```php
public function __construct(string $lang = 'en')
```

_No doc comment._

**Parameters**

+ `$lang` `string`, default `'en'`

Source: [framework/core/Validator.php:36](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Validator.php#L36)

<a name="validator-registerrules"></a>
#### `Validator::registerRules()`

```php
public static function registerRules()
```

Registers the rules exists and unique with GUMP, once. A rule of the same name that the app added first is kept.

Source: [framework/core/Validator.php:45](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Validator.php#L45)

<a name="validator-exists"></a>
#### `Validator::exists()`

```php
public static function exists(array $params, $value)
```

Whether a value is in table.column (the rule exists)

**Parameters**

+ `$params` `array`
+ `$value`

Source: [framework/core/Validator.php:71](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Validator.php#L71)

<a name="validator-unique"></a>
#### `Validator::unique()`

```php
public static function unique(array $params, $value, array $input = array())
```

Whether a value is not yet in table.column (the rule unique), ignoring the row whose column $params[1] equals
the input $params[2]

**Parameters**

+ `$params` `array`
+ `$value`
+ `$input` `array`, default `array()`

Source: [framework/core/Validator.php:81](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Validator.php#L81)

<a name="validator-normalize"></a>
#### `Validator::normalize()`

```php
public static function normalize($rules)
```

The rules as GUMP reads them: unique's extra arguments joined with ; (GUMP keeps one , only) and current_year
replaced by the year of today

**Parameters**

+ `$rules` `string|array`: 'required|max_numeric,current_year' (or GUMP's array form, kept as it is)

Source: [framework/core/Validator.php:101](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Validator.php#L101)

<a name="validator-validate"></a>
#### `->validate()`

```php
public function validate(array $input, array $ruleset)
```

_No doc comment._

**Parameters**

+ `$input` `array`
+ `$ruleset` `array`

Source: [framework/core/Validator.php:122](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Validator.php#L122)

<a name="validator-get-errors-array"></a>
#### `->get_errors_array()`

```php
public function get_errors_array()
```

The errors by field; exists and unique say what is missing or taken: "There is no such author",
"This email is already used" (GUMP::set_error_message() or the per-field messages replace them)

Source: [framework/core/Validator.php:131](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Validator.php#L131)

<a name="validator-check"></a>
#### `->check()`

```php
public function check($data, $rules = array(), $filters = array())
```

_No doc comment._

**Parameters**

+ `$data`
+ `$rules`, default `array()`
+ `$filters`, default `array()`

Source: [framework/core/Validator.php:172](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Validator.php#L172)

<a name="cache"></a>
## class Caligrafy\Cache

```php
namespace Caligrafy;

class Cache
```

Source: [framework/core/Cache.php:25](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Cache.php#L25)

Class Cache (2.18.0)

```
$rates = Cache::remember('exchange-rates', 600, fn () => $this->fetchRates());   // at most once every 10 minutes
Cache::put('report:2026-11', $rows, 3600);  Cache::get('report:2026-11', []);  Cache::forget('report:2026-11');
```

CACHE_STORE in .env: database (the default with DB_ACTIVATE=true: the caligrafy_cache table, which the deploy step
and php caligrafer.php platform install create, shared by the web server, the queue, scheduled jobs and every
server), file (the default without a database: a private folder of the temporary directory, of one server and one
system user, so the command line and the web server each have their own) or off (nothing is kept, remember()
always runs its function). Values are stored as JSON: strings, numbers, booleans,
null and arrays (an object comes back as an array). $seconds null keeps a value until it is forgotten or flushed.
php caligrafer.php cache clear empties the store.

### Constants

+ `TABLE = 'caligrafy_cache'`
+ `STORES = array('file', 'database', 'off')`

### Methods

+ [`Cache::store()`](#cache-store)
+ [`Cache::get()`](#cache-get)
+ [`Cache::has()`](#cache-has)
+ [`Cache::put()`](#cache-put)
+ [`Cache::forever()`](#cache-forever)
+ [`Cache::remember()`](#cache-remember)
+ [`Cache::forget()`](#cache-forget)
+ [`Cache::flush()`](#cache-flush)
+ [`Cache::clearMemory()`](#cache-clearmemory)

<a name="cache-store"></a>
#### `Cache::store()`

```php
public static function store()
```

The store in use: file, database or off

Source: [framework/core/Cache.php:36](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Cache.php#L36)

<a name="cache-get"></a>
#### `Cache::get()`

```php
public static function get($key, $default = null)
```

_No doc comment._

**Parameters**

+ `$key`
+ `$default`, default `null`

Source: [framework/core/Cache.php:70](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Cache.php#L70)

<a name="cache-has"></a>
#### `Cache::has()`

```php
public static function has($key)
```

_No doc comment._

**Parameters**

+ `$key`

Source: [framework/core/Cache.php:76](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Cache.php#L76)

<a name="cache-put"></a>
#### `Cache::put()`

```php
public static function put($key, $value, $seconds = null)
```

Keeps $value for $seconds (null: until forgotten)

**Parameters**

+ `$key`
+ `$value`
+ `$seconds`, default `null`

Source: [framework/core/Cache.php:84](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Cache.php#L84)

<a name="cache-forever"></a>
#### `Cache::forever()`

```php
public static function forever($key, $value)
```

Keeps $value forever (until forgotten or flushed)

**Parameters**

+ `$key`
+ `$value`

Source: [framework/core/Cache.php:123](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Cache.php#L123)

<a name="cache-remember"></a>
#### `Cache::remember()`

```php
public static function remember($key, $seconds, callable $make)
```

The cached value, or the result of $make, kept for $seconds

**Parameters**

+ `$key`
+ `$seconds`
+ `$make` `callable`

Source: [framework/core/Cache.php:131](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Cache.php#L131)

<a name="cache-forget"></a>
#### `Cache::forget()`

```php
public static function forget($key)
```

_No doc comment._

**Parameters**

+ `$key`

Source: [framework/core/Cache.php:142](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Cache.php#L142)

<a name="cache-flush"></a>
#### `Cache::flush()`

```php
public static function flush()
```

Empties the store

**Returns** `int|null`: how many values were removed (null when unknown)

Source: [framework/core/Cache.php:159](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Cache.php#L159)

<a name="cache-clearmemory"></a>
#### `Cache::clearMemory()`

```php
public static function clearMemory()
```

Forgets this request's copies (tests, a long worker)

Source: [framework/core/Cache.php:179](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Cache.php#L179)

<a name="lazy"></a>
## class Caligrafy\Lazy

```php
namespace Caligrafy;

class Lazy
```

Source: [framework/core/Model.php:705](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L705)

#[Caligrafy\Lazy] on a relation method of a model (2.26.0): it may load lazily, without [ERROR 2004] or a warning

_No public methods._

<a name="lazyloadingexception"></a>
## class Caligrafy\LazyLoadingException

```php
namespace Caligrafy;

class LazyLoadingException extends \LogicException
```

Source: [framework/core/Model.php:697](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L697)

Thrown in development when a relation loads lazily on one of several models a query read ([ERROR 2004], 2.26.0)

_No public methods._


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Model -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Caligrafy\Model

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Part of [Data](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data).

<a name="model"></a>
```php
namespace Caligrafy;

class Model extends \stdClass
```

Source: [framework/core/Model.php:20](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L20)

Class Model is the base model from which the application models can be extended

## Public properties

+ `public $table`
+ `public static $strictRelations = null`: Lazy loading of relations (2.26.0). A model the query builder read among several rows (Book::where(...)-&gt;get(), paginate(), chunk()) that runs a relation method (hasOne, hasMany, belongsTo, belongsToMany) would run one query per row (N+1): in development that throws [ERROR 2004]; in production (or with STRICT_RELATIONS=false) it logs a warning once per request and relation. $book-&gt;lazy()-&gt;author() allows one call, #[Caligrafy\Lazy] on the relation method allows it always. A model read alone (find(), first(), the instance find() and all()) is not guarded.

## Methods

+ [`->__construct()`](#model-construct)
+ [`->__invoke()`](#model-invoke)
+ [`->associate()`](#model-associate)
+ [`->create()`](#model-create)
+ [`->update()`](#model-update)
+ [`->delete()`](#model-delete)
+ [`->__call()`](#model-call)
+ [`Model::__callStatic()`](#model-callstatic)
+ [`->all()`](#model-all)
+ [`->search()`](#model-search)
+ [`->save()`](#model-save)
+ [`->hasOne()`](#model-hasone)
+ [`->hasMany()`](#model-hasmany)
+ [`->belongsTo()`](#model-belongsto)
+ [`->belongsToMany()`](#model-belongstomany)
+ [`->attach()`](#model-attach)
+ [`->detach()`](#model-detach)
+ [`->lazy()`](#model-lazy)
+ [`Model::collected()`](#model-collected)
+ [`Model::strictRelations()`](#model-strictrelations)
+ [`Model::forgetLazyWarnings()`](#model-forgetlazywarnings)
+ [`->arrayToModel()`](#model-arraytomodel)
+ [`->toArray()`](#model-toarray)
+ [`->tableExists()`](#model-tableexists)

<a name="model-construct"></a>
### `->__construct()`

```php
public function __construct($table = null)
```

_No doc comment._

**Parameters**

+ `$table`, default `null`

Source: [framework/core/Model.php:47](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L47)

<a name="model-invoke"></a>
### `->__invoke()`

```php
public function __invoke($table = null, $dynamicArgs = array())
```

_No doc comment._

**Parameters**

+ `$table`, default `null`
+ `$dynamicArgs`, default `array()`

Source: [framework/core/Model.php:52](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L52)

<a name="model-associate"></a>
### `->associate()`

```php
public function associate($table)
```

Associates a model with a table in the database

**Parameters**

+ `$table`

Source: [framework/core/Model.php:66](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L66)

<a name="model-create"></a>
### `->create()`

```php
public function create($inputs)
```

Basic CRUD functions on the associated table

**Parameters**

+ `$inputs`

Source: [framework/core/Model.php:77](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L77)

<a name="model-update"></a>
### `->update()`

```php
public function update($inputs, $id)
```

_No doc comment._

**Parameters**

+ `$inputs`
+ `$id`

Source: [framework/core/Model.php:99](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L99)

<a name="model-delete"></a>
### `->delete()`

```php
public function delete($id)
```

_No doc comment._

**Parameters**

+ `$id`

Source: [framework/core/Model.php:117](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L117)

<a name="model-call"></a>
### `->__call()`

```php
public function __call($method, $args)
```

$book-&gt;find($id) (instance: SELECT * FROM &lt;its table&gt; WHERE id = ?, as before) and $book-&gt;where(...) etc.

**Parameters**

+ `$method`
+ `$args`

Source: [framework/core/Model.php:150](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L150)

<a name="model-callstatic"></a>
### `Model::__callStatic()`

```php
public static function __callStatic($method, $args)
```

Book::query(), Book::find($id), Book::where(...), Book::with(...), Book::paginate(20)...

**Parameters**

+ `$method`
+ `$args`

Source: [framework/core/Model.php:166](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L166)

<a name="model-all"></a>
### `->all()`

```php
public function all($args = array())
```

Fetches all the records, optionally completed by SQL clauses

**Parameters**

+ `$args` `array`, default `array()`: 'condition' (ex: 'WHERE price &gt; ?'), 'order' (ex: 'ORDER BY title'), 'limit' (ex: 'LIMIT 10') and 'bindings' (array of values bound to the ? placeholders). The clauses are inserted as is: never concatenate user input in them, use ? placeholders and 'bindings' instead.

Source: [framework/core/Model.php:198](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L198)

<a name="model-search"></a>
### `->search()`

```php
public function search($scope, $keywords)
```

Search functionality that searched records in a table

**Parameters**

+ `$scope` `string`: defines the columns to search in the database separated by commas
+ `$keywords` `string`: defines the LIKE pattern to look for (% and _ are wildcards). It is bound, never inlined.

**Returns** `array`: $result results found in the database

Source: [framework/core/Model.php:227](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L227)

<a name="model-save"></a>
### `->save()`

```php
public function save()
```

Save functionality applied directly to the object that could update or create depending on whether the object has an id or not

Source: [framework/core/Model.php:307](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L307)

<a name="model-hasone"></a>
### `->hasOne()`

```php
public function hasOne(
    $modelName,
    $joinedTableName,
    $foreignKey = null,
    $localKey = null,
    $functionName = null
)
```

Defines the hasOne relationship

**Parameters**

+ `$modelName` `string`: defines the name of the model to join to
+ `$joinedTableName` `string`: defines the name of the table to join to
+ `$foreignKey` `string`, default `null`: defines the identifier key of the key indexing the joined table
+ `$localKey` `string`, default `null`: defines the identifier key of the joined table
+ `$functionName`, default `null`

**Returns** `Model`: object containing the records from the join

Source: [framework/core/Model.php:324](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L324)

<a name="model-hasmany"></a>
### `->hasMany()`

```php
public function hasMany(
    $modelName,
    $joinedTableName,
    $foreignKey = null,
    $localKey = null,
    $functionName = null
)
```

Defines the hasMany relationship

**Parameters**

+ `$modelName` `string`: defines the name of the model to join to
+ `$joinedTableName` `string`: defines the name of the table to join to
+ `$foreignKey` `string`, default `null`: defines the identifier key of the key indexing the joined table
+ `$localKey` `string`, default `null`: defines the identifier key of the joined table
+ `$functionName`, default `null`

**Returns** `Model`: object containing the records from the join

Source: [framework/core/Model.php:355](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L355)

<a name="model-belongsto"></a>
### `->belongsTo()`

```php
public function belongsTo($modelName, $joinedTableName, $foreignKey = null, $localKey = null)
```

_No doc comment._

**Parameters**

+ `$modelName`
+ `$joinedTableName`
+ `$foreignKey`, default `null`
+ `$localKey`, default `null`

Source: [framework/core/Model.php:378](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L378)

<a name="model-belongstomany"></a>
### `->belongsToMany()`

```php
public function belongsToMany(
    $modelName,
    $joinedTableName,
    $foreignKeyLocal = null,
    $foreignKeyJoin = null,
    $functionName = null
)
```

_No doc comment._

**Parameters**

+ `$modelName`
+ `$joinedTableName`
+ `$foreignKeyLocal`, default `null`
+ `$foreignKeyJoin`, default `null`
+ `$functionName`, default `null`

Source: [framework/core/Model.php:385](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L385)

<a name="model-attach"></a>
### `->attach()`

```php
public function attach($joinedTableName, $id)
```

_No doc comment._

**Parameters**

+ `$joinedTableName`
+ `$id`

Source: [framework/core/Model.php:452](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L452)

<a name="model-detach"></a>
### `->detach()`

```php
public function detach($joinedTableName, $id)
```

_No doc comment._

**Parameters**

+ `$joinedTableName`
+ `$id`

Source: [framework/core/Model.php:458](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L458)

<a name="model-lazy"></a>
### `->lazy()`

```php
public function lazy()
```

Allows the next relation call of this model to load lazily, once: $book-&gt;lazy()-&gt;author()
(a relation read on purpose for one of several rows)

**Returns** `$this`

Source: [framework/core/Model.php:499](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L499)

<a name="model-collected"></a>
### `Model::collected()`

```php
public static function collected(array $models, array $loaded = array())
```

Marks the models a query read together (Query::get() with more than one row): their relation methods are then
guarded against lazy loading. Called by the query builder.

**Parameters**

+ `$models` `array`: the models of one result
+ `$loaded` `array`, default `array()`: the relations the query loaded with with()

Source: [framework/core/Model.php:512](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L512)

<a name="model-strictrelations"></a>
### `Model::strictRelations()`

```php
public static function strictRelations()
```

Whether a lazy relation call throws: false in production (APP_ENV=production) and with STRICT_RELATIONS=false,
true otherwise. Decided once; Model::$strictRelations = true|false forces it, null decides again.

Source: [framework/core/Model.php:526](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L526)

<a name="model-forgetlazywarnings"></a>
### `Model::forgetLazyWarnings()`

```php
public static function forgetLazyWarnings()
```

Forgets the lazy loading warnings given so far (a new request: Query::forgetShapes() calls it)

Source: [framework/core/Model.php:539](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L539)

<a name="model-arraytomodel"></a>
### `->arrayToModel()`

```php
public function arrayToModel($array)
```

Turns an array into a Model

**Parameters**

+ `$array` `array`: takes the array that needs to be converted to a model

**Returns** `Model`: object containing the modified object

Source: [framework/core/Model.php:613](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L613)

<a name="model-toarray"></a>
### `->toArray()`

```php
public function toArray()
```

Turns Model into an array

**Returns** `array`: representation of the model

Source: [framework/core/Model.php:628](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L628)

<a name="model-tableexists"></a>
### `->tableExists()`

```php
public function tableExists($tablename)
```

Checks if a table exists

**Parameters**

+ `$tablename`

**Returns** `boolean`: of the result

Source: [framework/core/Model.php:668](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Model.php#L668)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Query -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Caligrafy\Query

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Part of [Data](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data).

<a name="query"></a>
```php
namespace Caligrafy;

class Query
```

Source: [framework/core/Query.php:29](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L29)

Class Query
Builds one SQL statement with bound values only. Table and column names are validated against IDENTIFIER and
quoted with backticks, operators come from an allow-list, values are never written into the SQL.

```
Database::table('books')->where('price', '<', 20)->orderBy('title')->limit(10)->get();   // arrays
Book::where('author_id', 3)->with('author', 'tags')->paginate(20);                       // Book models
```

Eager loading (with(), withCount()) runs one more query per relation (WHERE key IN (...), in chunks of 1000 keys)
and attaches its rows under the relation's name; it never joins in a way that repeats the main rows.
In development (APP_ENV other than production) the same SELECT shape run 10 times in one request is logged once
as a probable N+1 query (error_log), with the file and line that ran it.
The models of a result of several rows are guarded (2.26.0): a relation method run on one of them throws [ERROR 2004]
in development and logs a warning in production (Model::strictRelations(), STRICT_RELATIONS=false, $model-&gt;lazy()).

## Constants

+ `IDENTIFIER = '/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/'`
+ `NAME = '/^[A-Za-z_][A-Za-z0-9_]*$/'`
+ `IN_CHUNK = 1000`
+ `NO_LIMIT = '9223372036854775807'`

## Public properties

+ `public static $threshold = 10`: int identical SELECT shapes in a request before the N+1 warning
+ `public static $logger = null`: callable|null receives the N+1 warning instead of error_log()
+ `public static $watching = null`: bool|null null until the first query decides it from APP_ENV (see watching())

## Methods

+ [`->__construct()`](#query-construct)
+ [`Query::useExecutor()`](#query-useexecutor)
+ [`Query::watching()`](#query-watching)
+ [`Query::watch()`](#query-watch)
+ [`Query::forgetShapes()`](#query-forgetshapes)
+ [`Query::observe()`](#query-observe)
+ [`Query::shape()`](#query-shape)
+ [`Query::caller()`](#query-caller)
+ [`Query::quote()`](#query-quote)
+ [`Query::plural()`](#query-plural)
+ [`Query::singular()`](#query-singular)
+ [`->select()`](#query-select)
+ [`->where()`](#query-where)
+ [`->orWhere()`](#query-orwhere)
+ [`->whereIn()`](#query-wherein)
+ [`->whereNotIn()`](#query-wherenotin)
+ [`->whereNull()`](#query-wherenull)
+ [`->whereNotNull()`](#query-wherenotnull)
+ [`->whereBetween()`](#query-wherebetween)
+ [`->search()`](#query-search)
+ [`->orderBy()`](#query-orderby)
+ [`->latest()`](#query-latest)
+ [`->oldest()`](#query-oldest)
+ [`->limit()`](#query-limit)
+ [`->offset()`](#query-offset)
+ [`->input()`](#query-input)
+ [`->models()`](#query-models)
+ [`->arrays()`](#query-arrays)
+ [`->with()`](#query-with)
+ [`->withCount()`](#query-withcount)
+ [`Query::relation()`](#query-relation)
+ [`->toSql()`](#query-tosql)
+ [`->getBindings()`](#query-getbindings)
+ [`->get()`](#query-get)
+ [`->first()`](#query-first)
+ [`->find()`](#query-find)
+ [`->value()`](#query-value)
+ [`->pluck()`](#query-pluck)
+ [`->count()`](#query-count)
+ [`->exists()`](#query-exists)
+ [`->paginate()`](#query-paginate)
+ [`->chunk()`](#query-chunk)
+ [`->insert()`](#query-insert)
+ [`->update()`](#query-update)
+ [`->delete()`](#query-delete)
+ [`->increment()`](#query-increment)
+ [`->decrement()`](#query-decrement)

<a name="query-construct"></a>
### `->__construct()`

```php
public function __construct($table)
```

**Parameters**

+ `$table` `string`: a table name (letters, digits, _; one optional schema prefix: db.table)

Source: [framework/core/Query.php:78](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L78)

<a name="query-useexecutor"></a>
### `Query::useExecutor()`

```php
public static function useExecutor($executor = null)
```

Sends the queries of the builder to $executor instead of Database (tests, another connection)

**Parameters**

+ `$executor` `object|null`, default `null`: execute(string $sql, array $bindings): array of rows; optional lastInsertId() and rowCount(); null goes back to Database

Source: [framework/core/Query.php:93](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L93)

<a name="query-watching"></a>
### `Query::watching()`

```php
public static function watching()
```

Whether the N+1 detection is on: decided once, from APP_ENV (off with production); watch() forces it

Source: [framework/core/Query.php:104](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L104)

<a name="query-watch"></a>
### `Query::watch()`

```php
public static function watch($on = null)
```

Turns the N+1 detection on or off (null: from APP_ENV again) and forgets the shapes counted so far

**Parameters**

+ `$on`, default `null`

Source: [framework/core/Query.php:119](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L119)

<a name="query-forgetshapes"></a>
### `Query::forgetShapes()`

```php
public static function forgetShapes()
```

Forgets the shapes counted so far, keeping watch() as it is: a new request (Caligrafy\Testing\TestCase calls it
before each test, so queries of earlier tests never add up to a warning)

Source: [framework/core/Query.php:131](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L131)

<a name="query-observe"></a>
### `Query::observe()`

```php
public static function observe($sql)
```

Counts a SELECT by its shape (values, numbers and IN lists folded) and logs one warning when the same shape
reaches $threshold in the request. Called by Database::execute() and by the builder's own executor.

**Parameters**

+ `$sql`

Source: [framework/core/Query.php:142](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L142)

<a name="query-shape"></a>
### `Query::shape()`

```php
public static function shape($sql)
```

The shape of a query: string and number literals become ?, IN lists one ?, spaces one space, lower case

**Parameters**

+ `$sql`

Source: [framework/core/Query.php:168](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L168)

<a name="query-caller"></a>
### `Query::caller()`

```php
public static function caller()
```

The file and line of the first frame outside framework/ ("the framework" when there is none)

Source: [framework/core/Query.php:180](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L180)

<a name="query-quote"></a>
### `Query::quote()`

```php
public static function quote($name)
```

Validates an identifier (column, table, or table.column) and returns it quoted: `books`.`title`

**Parameters**

+ `$name`

Source: [framework/core/Query.php:194](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L194)

<a name="query-plural"></a>
### `Query::plural()`

```php
public static function plural($name)
```

The simple plural of a name: author -&gt; authors, category -&gt; categories, box/class/church/wish -&gt; ...es

**Parameters**

+ `$name`

Source: [framework/core/Query.php:214](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L214)

<a name="query-singular"></a>
### `Query::singular()`

```php
public static function singular($name)
```

The singular that plural() inverts: authors -&gt; author, categories -&gt; category, boxes -&gt; box

**Parameters**

+ `$name`

Source: [framework/core/Query.php:229](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L229)

<a name="query-select"></a>
### `->select()`

```php
public function select(...$columns)
```

The columns to read: select('id', 'title'), select(['id', 'title']), 'books.\*', 'title as name'

**Parameters**

+ `...$columns`

Source: [framework/core/Query.php:251](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L251)

<a name="query-where"></a>
### `->where()`

```php
public function where($column, $operator = null, $value = null)
```

where('price', '&lt;', 20), where('author_id', 3) (=), where(['status' =&gt; 'new', 'author_id' =&gt; 3]),
where(function ($q) { $q-&gt;where(...)-&gt;orWhere(...); }) for a group in parentheses.
A null value with = / != becomes IS NULL / IS NOT NULL.

**Parameters**

+ `$column`
+ `$operator`, default `null`
+ `$value`, default `null`

Source: [framework/core/Query.php:288](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L288)

<a name="query-orwhere"></a>
### `->orWhere()`

```php
public function orWhere($column, $operator = null, $value = null)
```

_No doc comment._

**Parameters**

+ `$column`
+ `$operator`, default `null`
+ `$value`, default `null`

Source: [framework/core/Query.php:298](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L298)

<a name="query-wherein"></a>
### `->whereIn()`

```php
public function whereIn($column, array $values)
```

whereIn('id', [1, 2, 3]); an empty list matches no row (0 = 1)

**Parameters**

+ `$column`
+ `$values` `array`

Source: [framework/core/Query.php:380](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L380)

<a name="query-wherenotin"></a>
### `->whereNotIn()`

```php
public function whereNotIn($column, array $values)
```

whereNotIn('id', [1, 2]); an empty list adds no condition

**Parameters**

+ `$column`
+ `$values` `array`

Source: [framework/core/Query.php:396](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L396)

<a name="query-wherenull"></a>
### `->whereNull()`

```php
public function whereNull($column)
```

_No doc comment._

**Parameters**

+ `$column`

Source: [framework/core/Query.php:409](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L409)

<a name="query-wherenotnull"></a>
### `->whereNotNull()`

```php
public function whereNotNull($column)
```

_No doc comment._

**Parameters**

+ `$column`

Source: [framework/core/Query.php:414](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L414)

<a name="query-wherebetween"></a>
### `->whereBetween()`

```php
public function whereBetween($column, array $range)
```

whereBetween('price', [10, 20]): both ends included

**Parameters**

+ `$column`
+ `$range` `array`

Source: [framework/core/Query.php:422](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L422)

<a name="query-search"></a>
### `->search()`

```php
public function search(array $columns, $keywords)
```

search(['title', 'summary'], 'php mvc'): (title LIKE ? OR summary LIKE ?) with %php mvc% bound, % and _ of
the keywords escaped so they match themselves. Empty keywords add no condition.

**Parameters**

+ `$columns` `array`
+ `$keywords`

Source: [framework/core/Query.php:435](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L435)

<a name="query-orderby"></a>
### `->orderBy()`

```php
public function orderBy($column, $direction = 'asc')
```

orderBy('title'), orderBy('created_at', 'desc')

**Parameters**

+ `$column`
+ `$direction`, default `'asc'`

Source: [framework/core/Query.php:457](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L457)

<a name="query-latest"></a>
### `->latest()`

```php
public function latest($column = 'created_at')
```

_No doc comment._

**Parameters**

+ `$column`, default `'created_at'`

Source: [framework/core/Query.php:469](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L469)

<a name="query-oldest"></a>
### `->oldest()`

```php
public function oldest($column = 'created_at')
```

_No doc comment._

**Parameters**

+ `$column`, default `'created_at'`

Source: [framework/core/Query.php:474](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L474)

<a name="query-limit"></a>
### `->limit()`

```php
public function limit($count)
```

_No doc comment._

**Parameters**

+ `$count`

Source: [framework/core/Query.php:479](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L479)

<a name="query-offset"></a>
### `->offset()`

```php
public function offset($count)
```

_No doc comment._

**Parameters**

+ `$count`

Source: [framework/core/Query.php:485](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L485)

<a name="query-input"></a>
### `->input()`

```php
public function input(array $input)
```

The input paginate() reads the page from (instead of $_GET): -&gt;input($request-&gt;parameters)

**Parameters**

+ `$input` `array`

Source: [framework/core/Query.php:505](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L505)

<a name="query-models"></a>
### `->models()`

```php
public function models($class = Model::class)
```

Rows become instances of $class (a Model) through its arrayToModel()

**Parameters**

+ `$class`, default `Model::class`

Source: [framework/core/Query.php:514](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L514)

<a name="query-arrays"></a>
### `->arrays()`

```php
public function arrays()
```

Rows stay associative arrays (the default of Database::table(), and undoes models())

Source: [framework/core/Query.php:526](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L526)

<a name="query-with"></a>
### `->with()`

```php
public function with(...$relations)
```

with('author', 'tags', 'author.country'), with(['author' =&gt; ['table' =&gt; 'people', 'foreign_key' =&gt; 'writer_id']]),
with(['tags' =&gt; ['pivot' =&gt; 'tag_links']]), with(['books' =&gt; function (Query $q) { $q-&gt;where('published', 1); }])

**Parameters**

+ `...$relations`

Source: [framework/core/Query.php:536](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L536)

<a name="query-withcount"></a>
### `->withCount()`

```php
public function withCount(...$relations)
```

withCount('books'): adds books_count to each row (hasMany or belongsToMany), one GROUP BY query

**Parameters**

+ `...$relations`

Source: [framework/core/Query.php:555](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L555)

<a name="query-relation"></a>
### `Query::relation()`

```php
public static function relation($parent, $name, $config = null)
```

How a relation of $parent is read, by convention unless $config says otherwise:

- singular name (author) on books: belongsTo, books.author_id -&gt; authors.id
- plural name (books) on authors: hasMany, books.author_id = authors.id
- ['pivot' =&gt; true|'name'] or type belongsToMany (tags on books): the pivot Model::belongsToMany() creates, books_tags (&lt;this table&gt;_&lt;related table&gt;), or tags_books when only that one exists (tried when books_tags fails, then remembered); books_tags.book_id = books.id, books_tags.tag_id = tags.id

**Parameters**

+ `$parent`
+ `$name`
+ `$config`, default `null`

**Returns** `array`: type, table, foreign_key, local_key, owner_key, pivot, related_key, query

Source: [framework/core/Query.php:641](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L641)

<a name="query-tosql"></a>
### `->toSql()`

```php
public function toSql()
```

The SELECT this query runs (placeholders for the values: see getBindings())

Source: [framework/core/Query.php:696](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L696)

<a name="query-getbindings"></a>
### `->getBindings()`

```php
public function getBindings()
```

_No doc comment._

Source: [framework/core/Query.php:715](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L715)

<a name="query-get"></a>
### `->get()`

```php
public function get()
```

The rows: arrays, or models after models() (Book::query() hydrates Book by default)

Source: [framework/core/Query.php:738](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L738)

<a name="query-first"></a>
### `->first()`

```php
public function first()
```

_No doc comment._

Source: [framework/core/Query.php:760](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L760)

<a name="query-find"></a>
### `->find()`

```php
public function find($id, $column = 'id')
```

_No doc comment._

**Parameters**

+ `$id`
+ `$column`, default `'id'`

Source: [framework/core/Query.php:768](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L768)

<a name="query-value"></a>
### `->value()`

```php
public function value($column)
```

The value of one column of the first row, or null

**Parameters**

+ `$column`

Source: [framework/core/Query.php:776](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L776)

<a name="query-pluck"></a>
### `->pluck()`

```php
public function pluck($column, $key = null)
```

pluck('title') -&gt; ['A', 'B']; pluck('title', 'id') -&gt; [1 =&gt; 'A', 2 =&gt; 'B']

**Parameters**

+ `$column`
+ `$key`, default `null`

Source: [framework/core/Query.php:788](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L788)

<a name="query-count"></a>
### `->count()`

```php
public function count()
```

_No doc comment._

Source: [framework/core/Query.php:811](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L811)

<a name="query-exists"></a>
### `->exists()`

```php
public function exists()
```

_No doc comment._

Source: [framework/core/Query.php:822](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L822)

<a name="query-paginate"></a>
### `->paginate()`

```php
public function paginate($perPage = 20, $page = null)
```

paginate(20): ['data' =&gt; rows, 'total' =&gt; n, 'page' =&gt; p, 'per_page' =&gt; 20, 'pages' =&gt; m]
$page null reads 'page' from input() or $_GET; anything but a whole number &gt;= 1 is page 1.
A page past the last one returns no rows (and runs no second query).

**Parameters**

+ `$perPage`, default `20`
+ `$page`, default `null`

Source: [framework/core/Query.php:837](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L837)

<a name="query-chunk"></a>
### `->chunk()`

```php
public function chunk($size, callable $callback)
```

Runs $callback($rows, $chunkNumber) on chunks of $size rows (ordered by id unless the query has an order);
a callback that returns false stops. Returns false when stopped, true otherwise.

**Parameters**

+ `$size`
+ `$callback` `callable`

Source: [framework/core/Query.php:871](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L871)

<a name="query-insert"></a>
### `->insert()`

```php
public function insert(array $values)
```

insert(['title' =&gt; 'A', 'price' =&gt; 10]) or insert([[...], [...]]) (one INSERT for every row, same columns).
Arrays and objects are saved as JSON, booleans as 0/1. Returns the last insert id.

**Parameters**

+ `$values` `array`

Source: [framework/core/Query.php:918](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L918)

<a name="query-update"></a>
### `->update()`

```php
public function update(array $values)
```

update(['price' =&gt; 12]): needs a where() (LogicException otherwise). Returns the number of rows changed.

**Parameters**

+ `$values` `array`

Source: [framework/core/Query.php:948](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L948)

<a name="query-delete"></a>
### `->delete()`

```php
public function delete()
```

delete(): needs a where() (LogicException otherwise). Returns the number of rows deleted.

Source: [framework/core/Query.php:966](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L966)

<a name="query-increment"></a>
### `->increment()`

```php
public function increment($column, $amount = 1, array $extra = array())
```

increment('views'), increment('stock', 5, ['restocked_at' =&gt; date('Y-m-d H:i:s')]): needs a where()

**Parameters**

+ `$column`
+ `$amount`, default `1`
+ `$extra` `array`, default `array()`

Source: [framework/core/Query.php:975](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L975)

<a name="query-decrement"></a>
### `->decrement()`

```php
public function decrement($column, $amount = 1, array $extra = array())
```

_No doc comment._

**Parameters**

+ `$column`
+ `$amount`, default `1`
+ `$extra` `array`, default `array()`

Source: [framework/core/Query.php:980](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Query.php#L980)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Auth -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Sign-in

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Users and sessions, passkeys and face login.

| Class | What it is |
|---|---|
| [`Caligrafy\Auth`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Auth#auth) | Class that defines the properties and methods of an authentication mechanism for UI and API |
| [`Caligrafy\Passkey`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Auth#passkey) | Passkey wraps lbuchs/webauthn (MIT, no dependencies besides ext-openssl). |
| [`Caligrafy\PasskeyException`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Auth#passkeyexception) | (no doc comment) |
| [`Caligrafy\FaceLogin`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Auth#facelogin) | Face login checks used with FaceDetector.liveness() (public/js/services/detect.js) |
| [`Caligrafy\FaceLoginException`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Auth#faceloginexception) | (no doc comment) |

<a name="auth"></a>
## class Caligrafy\Auth

```php
namespace Caligrafy;

class Auth extends \stdClass
```

Source: [framework/core/Auth.php:19](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Auth.php#L19)

Class that defines the properties and methods of an authentication mechanism for UI and API

### Public properties

+ `public static $api = false`

### Methods

+ [`Auth::activateAPI()`](#auth-activateapi)
+ [`Auth::authentication()`](#auth-authentication)
+ [`Auth::authorize()`](#auth-authorize)
+ [`Auth::unauthorize()`](#auth-unauthorize)
+ [`Auth::api()`](#auth-api)
+ [`Auth::active()`](#auth-active)
+ [`Auth::model()`](#auth-model)
+ [`Auth::reset()`](#auth-reset)
+ [`Auth::find()`](#auth-find)
+ [`Auth::authorized()`](#auth-authorized)
+ [`Auth::guard()`](#auth-guard)
+ [`Auth::logout()`](#auth-logout)
+ [`Auth::user()`](#auth-user)

<a name="auth-activateapi"></a>
#### `Auth::activateAPI()`

```php
public static function activateAPI()
```

Activate API by creating an API token

**Returns** `boolean`: of success of completion of the method

Source: [framework/core/Auth.php:29](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Auth.php#L29)

<a name="auth-authentication"></a>
#### `Auth::authentication()`

```php
public static function authentication($modelname, $tablename)
```

Activate User Authentication - instructs the framework that an authentication can be used

**Parameters**

+ `$modelname`: defines the name of the model associated with the Authentication
+ `$tablename`: defines the name of the database table associated with the Authentication

**Returns** `boolean`: of success of completion of the method

Source: [framework/core/Auth.php:40](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Auth.php#L40)

<a name="auth-authorize"></a>
#### `Auth::authorize()`

```php
public static function authorize($user)
```

Method used upon login to authorize the logged in user

**Parameters**

+ `$user` `Model`: defines the user model that needs to be authorized

**Returns** `boolean`: of success of completion of the method

Source: [framework/core/Auth.php:52](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Auth.php#L52)

<a name="auth-unauthorize"></a>
#### `Auth::unauthorize()`

```php
public static function unauthorize()
```

Method used upon logout to unauthorize all users

Source: [framework/core/Auth.php:64](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Auth.php#L64)

<a name="auth-api"></a>
#### `Auth::api()`

```php
public static function api()
```

Getter that returns the API token

Source: [framework/core/Auth.php:71](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Auth.php#L71)

<a name="auth-active"></a>
#### `Auth::active()`

```php
public static function active()
```

Whether authentication is set up (Auth::authentication() was called in web.php)

Source: [framework/core/Auth.php:79](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Auth.php#L79)

<a name="auth-model"></a>
#### `Auth::model()`

```php
public static function model()
```

A copy of the authentication model (null when authentication is off): Route::auth() finds users with it

Source: [framework/core/Auth.php:87](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Auth.php#L87)

<a name="auth-reset"></a>
#### `Auth::reset()`

```php
public static function reset()
```

Turns authentication off again (tests)

Source: [framework/core/Auth.php:95](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Auth.php#L95)

<a name="auth-find"></a>
#### `Auth::find()`

```php
public static function find($id)
```

Loads a user by id with the authentication model (null when authentication is off or the user does not exist)

**Parameters**

+ `$id`

Source: [framework/core/Auth.php:103](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Auth.php#L103)

<a name="auth-authorized"></a>
#### `Auth::authorized()`

```php
public static function authorized()
```

Method that checks if the user in session is authorized to perform actions

**Returns** `boolean`: of whether or not the user is valid and allowed to perform actions

Source: [framework/core/Auth.php:117](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Auth.php#L117)

<a name="auth-guard"></a>
#### `Auth::guard()`

```php
public static function guard(
    $permissionAttribute,
    $acceptedPermission,
    $loginUrl = "/login",
    $notAuthorized = '/notAuthorized'
)
```

Method that checks if the user in session has permissions to access

**Parameters**

+ `$permissionAttribute`
+ `$acceptedPermission`
+ `$loginUrl`, default `"/login"`
+ `$notAuthorized`, default `'/notAuthorized'`

**Returns** `boolean`: of whether or not the user is valid and allowed to perform actions

Source: [framework/core/Auth.php:132](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Auth.php#L132)

<a name="auth-logout"></a>
#### `Auth::logout()`

```php
public static function logout($redirectUrl = '/')
```

Method that logs the user out

**Parameters**

+ `$redirectUrl`, default `'/'`

Source: [framework/core/Auth.php:150](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Auth.php#L150)

<a name="auth-user"></a>
#### `Auth::user()`

```php
public static function user()
```

Method that returns the currently logged in user

**Returns** `currently`: logged in user

Source: [framework/core/Auth.php:164](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Auth.php#L164)

<a name="passkey"></a>
## class Caligrafy\Passkey

```php
namespace Caligrafy;

class Passkey extends \stdClass
```

Source: [framework/core/Passkey.php:34](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Passkey.php#L34)

Passkey wraps lbuchs/webauthn (MIT, no dependencies besides ext-openssl). The browser side is
public/js/services/passkey.js (PasskeyClient.create() / PasskeyClient.get()).

Registration (logged-in user):  registrationOptions($id, $username) -&gt; navigator.credentials.create() -&gt; register($response, $id)
Authentication:                  authenticationOptions([$id])        -&gt; navigator.credentials.get()    -&gt; authenticate($response) returns the user id

The challenge of each ceremony is kept in the session: single use, it expires after $timeout seconds.
Relying party: PASSKEY_RP_ID (the domain, ex: example.com) and PASSKEY_ORIGIN (ex: https://www.example.com) in .env.
Without them the request host is used, which is fine in development: set both in production.
Passkeys need https, except on localhost.

Table (see the face login recipe / wiki 9.9.2):

```
passkeys (id, user_id, credential_id, public_key, sign_count, name, transports, aaguid, created_at, last_used_at)
```

### Constants

+ `SESSION_KEY = '__passkey_challenge'`

### Public properties

+ `public $timeout = 120`
+ `public $userVerification = 'required'`
+ `public $residentKey = 'required'`

### Methods

+ [`->__construct()`](#passkey-construct)
+ [`->rpId()`](#passkey-rpid)
+ [`->origin()`](#passkey-origin)
+ [`->registrationOptions()`](#passkey-registrationoptions)
+ [`->register()`](#passkey-register)
+ [`->authenticationOptions()`](#passkey-authenticationoptions)
+ [`->authenticate()`](#passkey-authenticate)
+ [`->credentials()`](#passkey-credentials)
+ [`->findCredential()`](#passkey-findcredential)
+ [`->remove()`](#passkey-remove)
+ [`Passkey::toBase64Url()`](#passkey-tobase64url)
+ [`Passkey::fromBase64Url()`](#passkey-frombase64url)

<a name="passkey-construct"></a>
#### `->__construct()`

```php
public function __construct($rpName = null, $rpId = null, $origin = null, $table = 'passkeys')
```

**Parameters**

+ `$rpName` `string|null`, default `null`: name shown by the browser (default APP_NAME or the rp id)
+ `$rpId` `string|null`, default `null`: domain (default PASSKEY_RP_ID, else the request host)
+ `$origin` `string|null`, default `null`: exact origin the browser must report (default PASSKEY_ORIGIN, else APP_PROTOCOL://request host)
+ `$table` `string`, default `'passkeys'`: credentials table

Source: [framework/core/Passkey.php:54](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Passkey.php#L54)

<a name="passkey-rpid"></a>
#### `->rpId()`

```php
public function rpId()
```

_No doc comment._

Source: [framework/core/Passkey.php:74](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Passkey.php#L74)

<a name="passkey-origin"></a>
#### `->origin()`

```php
public function origin()
```

_No doc comment._

Source: [framework/core/Passkey.php:75](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Passkey.php#L75)

<a name="passkey-registrationoptions"></a>
#### `->registrationOptions()`

```php
public function registrationOptions($userId, $userName, $displayName = null)
```

Options for navigator.credentials.create() (pass them to PasskeyClient.create())

**Parameters**

+ `$userId` `mixed`: id of the logged-in user (stored as the WebAuthn user handle: never an email or a name)
+ `$userName`
+ `$displayName`, default `null`

Source: [framework/core/Passkey.php:81](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Passkey.php#L81)

<a name="passkey-register"></a>
#### `->register()`

```php
public function register($response, $userId, $name = null)
```

Verifies the response of navigator.credentials.create() and stores the credential

**Parameters**

+ `$response` `array`: from PasskeyClient.create(): id, clientDataJSON, attestationObject, transports
+ `$userId`
+ `$name`, default `null`

**Returns** `array`: the stored credential (without the public key)

+ **@throws** PasskeyException

Source: [framework/core/Passkey.php:97](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Passkey.php#L97)

<a name="passkey-authenticationoptions"></a>
#### `->authenticationOptions()`

```php
public function authenticationOptions($userId = null)
```

Options for navigator.credentials.get() (pass them to PasskeyClient.get())

**Parameters**

+ `$userId` `mixed`, default `null`: Optional. Limits the prompt to this user's passkeys; null lets the browser offer any discoverable passkey of the site (login without a username)

Source: [framework/core/Passkey.php:135](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Passkey.php#L135)

<a name="passkey-authenticate"></a>
#### `->authenticate()`

```php
public function authenticate($response)
```

Verifies the response of navigator.credentials.get()

**Parameters**

+ `$response` `array`: from PasskeyClient.get(): id, clientDataJSON, authenticatorData, signature, userHandle

**Returns** `string`: the id of the user who owns the passkey

+ **@throws** PasskeyException (401)

Source: [framework/core/Passkey.php:150](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Passkey.php#L150)

<a name="passkey-credentials"></a>
#### `->credentials()`

```php
public function credentials($userId)
```

Storage: override these 4 methods to keep the credentials somewhere else

**Parameters**

+ `$userId`

Source: [framework/core/Passkey.php:179](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Passkey.php#L179)

<a name="passkey-findcredential"></a>
#### `->findCredential()`

```php
public function findCredential($credentialId)
```

_No doc comment._

**Parameters**

+ `$credentialId`

Source: [framework/core/Passkey.php:184](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Passkey.php#L184)

<a name="passkey-remove"></a>
#### `->remove()`

```php
public function remove($userId, $credentialId)
```

_No doc comment._

**Parameters**

+ `$userId`
+ `$credentialId`

Source: [framework/core/Passkey.php:201](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Passkey.php#L201)

<a name="passkey-tobase64url"></a>
#### `Passkey::toBase64Url()`

```php
public static function toBase64Url($binary)
```

_No doc comment._

**Parameters**

+ `$binary`

Source: [framework/core/Passkey.php:250](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Passkey.php#L250)

<a name="passkey-frombase64url"></a>
#### `Passkey::fromBase64Url()`

```php
public static function fromBase64Url($value)
```

_No doc comment._

**Parameters**

+ `$value`

Source: [framework/core/Passkey.php:256](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Passkey.php#L256)

<a name="passkeyexception"></a>
## class Caligrafy\PasskeyException

```php
namespace Caligrafy;

class PasskeyException extends \Exception
```

Source: [framework/core/Passkey.php:32](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Passkey.php#L32)

_No doc comment on this class._

_No public methods._

<a name="facelogin"></a>
## class Caligrafy\FaceLogin

```php
namespace Caligrafy;

class FaceLogin extends \stdClass
```

Source: [framework/core/FaceLogin.php:30](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/FaceLogin.php#L30)

Face login checks used with FaceDetector.liveness() (public/js/services/detect.js)

1. challenge($username) issues a nonce and $count of the CHALLENGES in a random order, kept in the session
2. the browser runs detector.liveness({ challenges }) and posts { nonce, liveness, prints }
3. verify($response, $username) consumes the nonce (single use, short lived) and checks the liveness result and the prints: enough of them, consistent with each other (same face) and not identical (a replayed static print)
4. match($prints, $enrolled) finds the account whose enrolled prints are close to every print

Face prints are computed in the browser: these checks stop photos, naive replays and stolen requests, they do not
stop a determined attacker who controls the browser. Use a passkey (Caligrafy\Passkey) for sensitive accounts.

Distances are euclidean between 128-number face-api descriptors: same person usually &lt; 0.5, others &gt; 0.6

### Constants

+ `SESSION_KEY = '__face_challenge'`
+ `CHALLENGES =['turn-left', 'turn-right', 'smile']`

### Public properties

+ `public static $match = 0.5`
+ `public static $spread = 0.6`
+ `public static $distinct = 0.001`
+ `public static $minPrints = 3`
+ `public static $maxPrints = 12`
+ `public static $count = 2`
+ `public static $ttl = 60`
+ `public static $clock = null`

### Methods

+ [`FaceLogin::challenge()`](#facelogin-challenge)
+ [`FaceLogin::consume()`](#facelogin-consume)
+ [`FaceLogin::verify()`](#facelogin-verify)
+ [`FaceLogin::checkPrints()`](#facelogin-checkprints)
+ [`FaceLogin::match()`](#facelogin-match)
+ [`FaceLogin::enrolledElsewhere()`](#facelogin-enrolledelsewhere)
+ [`FaceLogin::printHash()`](#facelogin-printhash)
+ [`FaceLogin::descriptor()`](#facelogin-descriptor)
+ [`FaceLogin::distance()`](#facelogin-distance)

<a name="facelogin-challenge"></a>
#### `FaceLogin::challenge()`

```php
public static function challenge($username = null, $count = null, $ttl = null)
```

Issues a new challenge and keeps it in the session (it replaces any previous one)

**Parameters**

+ `$username` `string|null`, default `null`: the account the check is for (null: 1:N login)
+ `$count` `int|null`, default `null`: number of challenges (1 to 3, default self::$count)
+ `$ttl`, default `null`

**Returns** `array`: ['nonce' =&gt; string, 'challenges' =&gt; [...], 'expires_in' =&gt; seconds]

Source: [framework/core/FaceLogin.php:55](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/FaceLogin.php#L55)

<a name="facelogin-consume"></a>
#### `FaceLogin::consume()`

```php
public static function consume($nonce, $username = null)
```

Takes the challenge out of the session: a nonce can be used once, even when the check then fails

**Parameters**

+ `$nonce`
+ `$username`, default `null`

**Returns** `array`: the challenge

+ **@throws** FaceLoginException (401) when there is no challenge, the nonce differs, it expired or is for another account

Source: [framework/core/FaceLogin.php:81](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/FaceLogin.php#L81)

<a name="facelogin-verify"></a>
#### `FaceLogin::verify()`

```php
public static function verify($response, $username = null)
```

Consumes the nonce and checks the liveness result and the prints of a response

**Parameters**

+ `$response` `array`: ['nonce' =&gt; .., 'liveness' =&gt; ['passed' =&gt; true, 'challenges' =&gt; [['name' =&gt;, 'passed' =&gt;], ..]], 'prints' =&gt; [[128 numbers] or ['descriptor' =&gt; [128 numbers]], ..]]
+ `$username`, default `null`

**Returns** `array`: the prints: [[128 floats], ..]

+ **@throws** FaceLoginException 401 (nonce) or 422 (liveness, prints)

Source: [framework/core/FaceLogin.php:105](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/FaceLogin.php#L105)

<a name="facelogin-checkprints"></a>
#### `FaceLogin::checkPrints()`

```php
public static function checkPrints($prints)
```

Validates the prints of one check: count, format, same face, not identical

**Parameters**

+ `$prints`

**Returns** `array`: [[128 floats], ..]

Source: [framework/core/FaceLogin.php:128](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/FaceLogin.php#L128)

<a name="facelogin-match"></a>
#### `FaceLogin::match()`

```php
public static function match($prints, $enrolled)
```

Finds the account that matches every print

**Parameters**

+ `$prints` `array`: [[128 floats], ..] from verify()
+ `$enrolled` `array`: [['user' =&gt; id, 'descriptor' =&gt; [128 floats]], ..]

**Returns** `array|null`: ['user' =&gt; id, 'distance' =&gt; mean distance] or null when no account matches

Source: [framework/core/FaceLogin.php:162](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/FaceLogin.php#L162)

<a name="facelogin-enrolledelsewhere"></a>
#### `FaceLogin::enrolledElsewhere()`

```php
public static function enrolledElsewhere($prints, $enrolled, $user = null)
```

Prints of a new enrolment must not match another account (one person, one account)

**Parameters**

+ `$prints`
+ `$enrolled`
+ `$user`, default `null`

**Returns** `mixed`: the id of the account that already has this face, or null

Source: [framework/core/FaceLogin.php:188](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/FaceLogin.php#L188)

<a name="facelogin-printhash"></a>
#### `FaceLogin::printHash()`

```php
public static function printHash($descriptor)
```

Hash of a print to remember the prints already accepted (an exact replay with a new nonce is refused)

**Parameters**

+ `$descriptor`

Source: [framework/core/FaceLogin.php:203](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/FaceLogin.php#L203)

<a name="facelogin-descriptor"></a>
#### `FaceLogin::descriptor()`

```php
public static function descriptor($d)
```

128 finite numbers as floats, or null

**Parameters**

+ `$d`

Source: [framework/core/FaceLogin.php:211](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/FaceLogin.php#L211)

<a name="facelogin-distance"></a>
#### `FaceLogin::distance()`

```php
public static function distance($a, $b)
```

_No doc comment._

**Parameters**

+ `$a`
+ `$b`

Source: [framework/core/FaceLogin.php:224](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/FaceLogin.php#L224)

<a name="faceloginexception"></a>
## class Caligrafy\FaceLoginException

```php
namespace Caligrafy;

class FaceLoginException extends \Exception
```

Source: [framework/core/FaceLogin.php:28](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/FaceLogin.php#L28)

_No doc comment on this class._

_No public methods._


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Jobs -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Jobs, notifications and mail

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Scheduled jobs, background jobs, web push and email notifications, mail.

| Class | What it is |
|---|---|
| [`Caligrafy\Scheduler`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Jobs#scheduler) | An app declares its jobs in application/config/schedule.php: each one calls one capability with fixed inputs on a fixed rhythm (every: 1m...1d, or a five-field cron in a timezone). |
| [`Caligrafy\Queue`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Jobs#queue) | A job is a capability and its input, kept in the caligrafy_jobs table (php caligrafer.php platform install, or the deploy step, creates it). |
| [`Caligrafy\Notify`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Notify#notify) | Notify::user($userId, ['title' =&gt; ..., 'body' =&gt; ..., 'url' =&gt; ..., 'tag' =&gt; ..., 'urgency' =&gt; ...]) sends to every channel the user turned on and logs the result (caligrafy_notifications: never the body; kept 30 days): ... |
| [`Caligrafy\Mail`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Jobs#mail) | The Mail class handles all emails sent from the framework |

<a name="scheduler"></a>
## class Caligrafy\Scheduler

```php
namespace Caligrafy;

class Scheduler
```

Source: [framework/core/Scheduler.php:22](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Scheduler.php#L22)

Class Scheduler
An app declares its jobs in application/config/schedule.php: each one calls one capability with fixed inputs on a
fixed rhythm (every: 1m...1d, or a five-field cron in a timezone). The framework validates the file, runs the jobs
locally (php caligrafer.php schedule due / work) and prints the listing Caligrafy Cloud runs in production
(schedule list --json, version 1).

A run: one at a time per job (a database lock), in a child process stopped at its timeout, with full access like the
command line (Context::system: actor type schedule, actor id the job's name), recorded in caligrafy_job_runs (kept 30
days). Exit codes: 0 ok, 1 the capability failed or timed out, 2 the schedule file is invalid, 3 skipped.

### Constants

+ `FILE = 'application/config/schedule.php'`
+ `TABLE = 'caligrafy_job_runs'`
+ `LISTING_VERSION = 1`
+ `EVERY = ...`
+ `DEFAULT_TIMEOUT = 55`
+ `MAX_TIMEOUT = 300`
+ `KEEP_DAYS = 30`
+ `FIELDS = array('name', 'capability', 'input', 'every', 'cron', 'timezone', 'timeout', 'enabled')`
+ `OK = 0`
+ `FAILED = 1`
+ `INVALID = 2`
+ `SKIPPED = 3`

### Methods

+ [`->__construct()`](#scheduler-construct)
+ [`->jobs()`](#scheduler-jobs)
+ [`Scheduler::validate()`](#scheduler-validate)
+ [`Scheduler::listing()`](#scheduler-listing)
+ [`Scheduler::parse()`](#scheduler-parse)
+ [`Scheduler::isDue()`](#scheduler-isdue)
+ [`->run()`](#scheduler-run)
+ [`->execute()`](#scheduler-execute)
+ [`->dueAt()`](#scheduler-dueat)
+ [`->due()`](#scheduler-due)
+ [`->work()`](#scheduler-work)
+ [`Scheduler::history()`](#scheduler-history)
+ [`Scheduler::spawn()`](#scheduler-spawn)

<a name="scheduler-construct"></a>
#### `->__construct()`

```php
public function __construct($root = '.')
```

_No doc comment._

**Parameters**

+ `$root`, default `'.'`

Source: [framework/core/Scheduler.php:42](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Scheduler.php#L42)

<a name="scheduler-jobs"></a>
#### `->jobs()`

```php
public function jobs($capabilities = true)
```

The jobs of the project's schedule file, validated and completed (an empty list when there is no file)

**Parameters**

+ `$capabilities` `bool`, default `true`: also check that each capability exists

+ **@throws** \InvalidArgumentException with every problem, one per line

Source: [framework/core/Scheduler.php:55](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Scheduler.php#L55)

<a name="scheduler-validate"></a>
#### `Scheduler::validate()`

```php
public static function validate(array $declared, ?callable $exists = null)
```

Validates declared jobs and completes them (cron from every, timezone, timeout, enabled)

**Parameters**

+ `$declared` `array`: the array the schedule file returns
+ `$exists` `?callable`, default `null`: tells whether a capability exists (null: not checked)

**Returns** `array`: the jobs, in the file's order

+ **@throws** \InvalidArgumentException with every problem, one per line

Source: [framework/core/Scheduler.php:75](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Scheduler.php#L75)

<a name="scheduler-listing"></a>
#### `Scheduler::listing()`

```php
public static function listing(array $jobs)
```

The listing Caligrafy Cloud reads at deploy time (schedule list --json): the enabled jobs, every as cron

**Parameters**

+ `$jobs` `array`

Source: [framework/core/Scheduler.php:149](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Scheduler.php#L149)

<a name="scheduler-parse"></a>
#### `Scheduler::parse()`

```php
public static function parse($cron)
```

The allowed values of each field of a five-field cron (minute hour day-of-month month day-of-week)

**Parameters**

+ `$cron`

**Returns** `array`: five sorted lists of integers (day of week: 0-6, Sunday is 0 or 7)

+ **@throws** \InvalidArgumentException

Source: [framework/core/Scheduler.php:168](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Scheduler.php#L168)

<a name="scheduler-isdue"></a>
#### `Scheduler::isDue()`

```php
public static function isDue($cron, \DateTimeInterface $at, $timezone = 'UTC')
```

Whether a cron is due at a time (to the minute), read in a timezone. When both the day of the month and the
day of the week are restricted, either one matches (as in cron)

**Parameters**

+ `$cron`
+ `$at` `\DateTimeInterface`
+ `$timezone`, default `'UTC'`

Source: [framework/core/Scheduler.php:225](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Scheduler.php#L225)

<a name="scheduler-run"></a>
#### `->run()`

```php
public function run($name, ?callable $say = null, $ifDue = false)
```

Runs one job now: takes its lock, runs it in a child process (stopped at its timeout), records the run

**Parameters**

+ `$name` `string`: the job's name
+ `$say` `?callable`, default `null`: prints a line
+ `$ifDue` `bool`, default `false`: only when the job is due this minute in its timezone (--if-due), else nothing is run or recorded

**Returns** `int`: an exit code (OK, FAILED, SKIPPED)

Source: [framework/core/Scheduler.php:254](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Scheduler.php#L254)

<a name="scheduler-execute"></a>
#### `->execute()`

```php
public function execute($name)
```

What a run's child process does: calls the job's capability as the scheduler and prints the result as JSON

**Parameters**

+ `$name`

**Returns** `int`: OK or FAILED

Source: [framework/core/Scheduler.php:286](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Scheduler.php#L286)

<a name="scheduler-dueat"></a>
#### `->dueAt()`

```php
public function dueAt(\DateTimeInterface $at)
```

The jobs due in a minute (enabled ones only)

**Parameters**

+ `$at` `\DateTimeInterface`

Source: [framework/core/Scheduler.php:305](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Scheduler.php#L305)

<a name="scheduler-due"></a>
#### `->due()`

```php
public function due(?callable $say = null, ?\DateTimeInterface $at = null)
```

Runs every job due in the current minute, side by side, and waits for them

**Parameters**

+ `$say` `?callable`, default `null`
+ `$at` `?\DateTimeInterface`, default `null`

**Returns** `int`: OK when every run is ok or skipped, FAILED otherwise

Source: [framework/core/Scheduler.php:316](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Scheduler.php#L316)

<a name="scheduler-work"></a>
#### `->work()`

```php
public function work(?callable $say = null)
```

Runs schedule due at the start of every minute until stopped (local development)

**Parameters**

+ `$say` `?callable`, default `null`

Source: [framework/core/Scheduler.php:341](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Scheduler.php#L341)

<a name="scheduler-history"></a>
#### `Scheduler::history()`

```php
public static function history($name = null, $limit = 50)
```

The latest runs, newest first

**Parameters**

+ `$name`, default `null`
+ `$limit`, default `50`

Source: [framework/core/Scheduler.php:358](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Scheduler.php#L358)

<a name="scheduler-spawn"></a>
#### `Scheduler::spawn()`

```php
public static function spawn(array $args, $root, $timeout)
```

Runs php caligrafer.php &lt;args&gt; in $root, stopped after $timeout seconds (the scheduler's jobs, the queue's jobs)

**Parameters**

+ `$args` `array`
+ `$root`
+ `$timeout`

**Returns** `array`: [exit code, or null when it was stopped, or false when it could not start; its output]

Source: [framework/core/Scheduler.php:400](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Scheduler.php#L400)

<a name="queue"></a>
## class Caligrafy\Queue

```php
namespace Caligrafy;

class Queue
```

Source: [framework/core/Queue.php:26](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Queue.php#L26)

Class Queue (2.18.0)

```
Queue::push('send_welcome_email', ['user_id' => $id]);                       // as soon as a worker is free
Queue::push('build_report', ['month' => '2026-11'], ['delay' => 600, 'attempts' => 5, 'timeout' => 120]);
```

A job is a capability and its input, kept in the caligrafy_jobs table (php caligrafer.php platform install, or the
deploy step, creates it). A worker runs each one in its own process, stopped at its timeout, with full access, as a
scheduled job (Context::system('queue', '&lt;capability&gt; #&lt;id&gt;')): check who may ask for the work before pushing it.

Workers: php caligrafer.php queue work (a loop, on your computer or your own server), or the scheduler: a job of
application/config/schedule.php on the framework's capability queue_work, every minute, which Caligrafy Cloud runs
too. A failed run is tried again after 30 s, 1 min, 2 min... until its attempts are used; an input the capability
refuses (invalid, not found) fails at once. Jobs are kept 7 days after they finish.

### Constants

+ `TABLE = 'caligrafy_jobs'`
+ `DEFAULT_ATTEMPTS = 3`
+ `DEFAULT_TIMEOUT = 60`
+ `MAX_TIMEOUT = 900`
+ `RETRY_SECONDS = 30`
+ `KEEP_DAYS = 7`
+ `NAME = '/^[a-z0-9_-]{1,40}$/'`

### Methods

+ [`Queue::push()`](#queue-push)
+ [`Queue::work()`](#queue-work)
+ [`Queue::execute()`](#queue-execute)
+ [`Queue::jobs()`](#queue-jobs)
+ [`Queue::counts()`](#queue-counts)
+ [`Queue::retry()`](#queue-retry)

<a name="queue-push"></a>
#### `Queue::push()`

```php
public static function push($capability, array $input = array(), array $options = array())
```

Adds a job

**Parameters**

+ `$capability`
+ `$input` `array`, default `array()`
+ `$options` `array`, default `array()`: delay (seconds), attempts (1-20), timeout (seconds), queue (a name, default)

**Returns** `int`: the job's id

Source: [framework/core/Queue.php:41](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Queue.php#L41)

<a name="queue-work"></a>
#### `Queue::work()`

```php
public static function work(array $options = array())
```

Runs jobs: until none is left (once), for $seconds, or forever

**Parameters**

+ `$options` `array`, default `array()`: queue (default), seconds (stop starting jobs after), once (stop when empty), sleep (seconds between looks when empty), root (the project), say (callable)

**Returns** `array`: counts: done, retried, failed

Source: [framework/core/Queue.php:69](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Queue.php#L69)

<a name="queue-execute"></a>
#### `Queue::execute()`

```php
public static function execute($id)
```

The child process of a job (php caligrafer.php queue exec &lt;id&gt;): calls its capability, prints its answer as JSON

**Parameters**

+ `$id`

**Returns** `int`: 0 done, 1 failed (try again), 2 refused (do not try again)

Source: [framework/core/Queue.php:111](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Queue.php#L111)

<a name="queue-jobs"></a>
#### `Queue::jobs()`

```php
public static function jobs($status = null, $limit = 50)
```

Jobs, newest first

**Parameters**

+ `$status` `string|null`, default `null`: pending, running, done or failed
+ `$limit`, default `50`

Source: [framework/core/Queue.php:136](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Queue.php#L136)

<a name="queue-counts"></a>
#### `Queue::counts()`

```php
public static function counts()
```

How many jobs are in each state

Source: [framework/core/Queue.php:150](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Queue.php#L150)

<a name="queue-retry"></a>
#### `Queue::retry()`

```php
public static function retry($id = null)
```

Puts failed jobs back in the queue with new attempts: one id, or all (null)

**Parameters**

+ `$id`, default `null`

**Returns** `int`: how many

Source: [framework/core/Queue.php:163](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Queue.php#L163)

<a name="notify"></a>
## class Caligrafy\Notify

Notify::user($userId, ['title' =&gt; ..., 'body' =&gt; ..., 'url' =&gt; ..., 'tag' =&gt; ..., 'urgency' =&gt; ...]) sends to every channel the user turned on and logs the result (caligrafy_notifications: never the body; kept 30 days): ...

Its 20 public methods have a page of their own: [Caligrafy\Notify](https://github.com/caligrafy/caligrafy-quill/wiki/API-Notify).

<a name="mail"></a>
## class Caligrafy\Mail

```php
namespace Caligrafy;

class Mail extends \stdClass
```

Source: [framework/core/Mail.php:24](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Mail.php#L24)

The Mail class handles all emails sent from the framework

### Methods

+ [`->__construct()`](#mail-construct)
+ [`->sendMail()`](#mail-sendmail)

<a name="mail-construct"></a>
#### `->__construct()`

```php
public function __construct()
```

_No doc comment._

Source: [framework/core/Mail.php:32](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Mail.php#L32)

<a name="mail-sendmail"></a>
#### `->sendMail()`

```php
public function sendMail($recipients, $emailContent, $from, array $headers = array())
```

**Parameters**

+ `$recipients`
+ `$emailContent`
+ `$from`
+ `$headers` `array`, default `array()`: extra headers, name =&gt; value (Notify: List-Unsubscribe, List-Unsubscribe-Post)

Source: [framework/core/Mail.php:73](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Mail.php#L73)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Notify -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Caligrafy\Notify

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Part of [Jobs, notifications and mail](https://github.com/caligrafy/caligrafy-quill/wiki/API-Jobs).

<a name="notify"></a>
```php
namespace Caligrafy;

class Notify
```

Source: [framework/core/Notify.php:28](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L28)

Class Notify
Notify::user($userId, ['title' =&gt; ..., 'body' =&gt; ..., 'url' =&gt; ..., 'tag' =&gt; ..., 'urgency' =&gt; ...]) sends to every
channel the user turned on and logs the result (caligrafy_notifications: never the body; kept 30 days):

- push: each browser the user subscribed (caligrafy_push_subscriptions), with the VAPID keys of .env (php caligrafer.php notify keys), 5 seconds per push service, the message kept 24 hours for a device that is off; a 404 or 410 deletes the subscription, so do 5 failures in a row
- email: the user's confirmed address only (caligrafy_notify_emails), through MAIL_*, with a one-click unsubscribe link (a signed URL) and the List-Unsubscribe headers

A delivery failure never throws; a bad message throws ServiceError::invalid. At most NOTIFY_RATE_PER_HOUR messages per
user and hour (30): above it nothing is sent ('skipped' =&gt; 'rate'). In-page alerts stay the app's job.
Without the tables (php caligrafer.php platform install) nothing is sent and nothing fails.

## Constants

+ `CHANNELS = array('push', 'email')`
+ `SUBSCRIPTIONS = 'caligrafy_push_subscriptions'`
+ `EMAILS = 'caligrafy_notify_emails'`
+ `PREFS = 'caligrafy_notify_prefs'`
+ `LOG = 'caligrafy_notifications'`
+ `TTL = 86400`
+ `PUSH_TIMEOUT = 5`
+ `MAX_FAILURES = 5`
+ `PAYLOAD_BYTES = 3072`
+ `TOKEN_HOURS = 24`
+ `KEEP_DAYS = 30`

## Public properties

+ `public static $pushSender = null`: callable|null replaces the push sender in tests: fn(array $subscriptions, string $payload, array $options) =&gt; [endpoint =&gt; status]
+ `public static $mailSender = null`: callable|null replaces the mail sender in tests: fn($to, $subject, $html, array $headers) =&gt; bool

## Methods

+ [`Notify::user()`](#notify-user)
+ [`Notify::forget()`](#notify-forget)
+ [`Notify::message()`](#notify-message)
+ [`Notify::pushConfigured()`](#notify-pushconfigured)
+ [`Notify::keys()`](#notify-keys)
+ [`Notify::subscribe()`](#notify-subscribe)
+ [`Notify::unsubscribe()`](#notify-unsubscribe)
+ [`Notify::emailConfigured()`](#notify-emailconfigured)
+ [`Notify::setEmail()`](#notify-setemail)
+ [`Notify::confirm()`](#notify-confirm)
+ [`Notify::unsubscribeUrl()`](#notify-unsubscribeurl)
+ [`Notify::unsubscribeEmail()`](#notify-unsubscribeemail)
+ [`Notify::html()`](#notify-html)
+ [`Notify::theme()`](#notify-theme)
+ [`Notify::page()`](#notify-page)
+ [`Notify::offered()`](#notify-offered)
+ [`Notify::prefer()`](#notify-prefer)
+ [`Notify::enabled()`](#notify-enabled)
+ [`Notify::status()`](#notify-status)
+ [`Notify::base()`](#notify-base)

<a name="notify-user"></a>
### `Notify::user()`

```php
public static function user($userId, array $message)
```

Sends a message to a user on every channel they turned on

**Parameters**

+ `$userId` `int|string`: the id Context::userId() returns
+ `$message` `array`: title (80), body (300), url (https or a path of the app), tag, urgency (low, normal, high)

**Returns** `array`: push (how many browsers got it), email (whether it was sent), skipped (null, or 'rate')

+ **@throws** ServiceError invalid, on a bad message

Source: [framework/core/Notify.php:58](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L58)

<a name="notify-forget"></a>
### `Notify::forget()`

```php
public static function forget($userId)
```

Deletes everything notifications keep about a user (their subscriptions, address, choices and log): call it when
you delete the user

**Parameters**

+ `$userId`

Source: [framework/core/Notify.php:90](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L90)

<a name="notify-message"></a>
### `Notify::message()`

```php
public static function message(array $message)
```

The message, checked and completed (urgency normal)

**Parameters**

+ `$message` `array`

+ **@throws** ServiceError invalid

Source: [framework/core/Notify.php:101](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L101)

<a name="notify-pushconfigured"></a>
### `Notify::pushConfigured()`

```php
public static function pushConfigured()
```

Whether the VAPID keys are set (php caligrafer.php notify keys)

Source: [framework/core/Notify.php:124](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L124)

<a name="notify-keys"></a>
### `Notify::keys()`

```php
public static function keys()
```

A new pair of VAPID keys (base64url): public and private

Source: [framework/core/Notify.php:132](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L132)

<a name="notify-subscribe"></a>
### `Notify::subscribe()`

```php
public static function subscribe($userId, array $subscription, $userAgent = '')
```

Saves a browser's push subscription (the JSON of PushSubscription) for a user; an endpoint belongs to one user

**Parameters**

+ `$userId`
+ `$subscription` `array`
+ `$userAgent`, default `''`

Source: [framework/core/Notify.php:142](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L142)

<a name="notify-unsubscribe"></a>
### `Notify::unsubscribe()`

```php
public static function unsubscribe($userId, $endpoint)
```

Deletes one of the user's subscriptions (only theirs): whether one was deleted

**Parameters**

+ `$userId`
+ `$endpoint`

Source: [framework/core/Notify.php:163](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L163)

<a name="notify-emailconfigured"></a>
### `Notify::emailConfigured()`

```php
public static function emailConfigured()
```

Whether email can be sent: MAIL_HOST set and an address for the app's links (APP_URL, or a web request)

Source: [framework/core/Notify.php:226](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L226)

<a name="notify-setemail"></a>
### `Notify::setEmail()`

```php
public static function setEmail($userId, $email)
```

Sets the user's address (one per user) and emails the confirmation link: valid 24 hours, used once

**Parameters**

+ `$userId`
+ `$email`

**Returns** `array`: the address, and whether the link was sent

Source: [framework/core/Notify.php:236](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L236)

<a name="notify-confirm"></a>
### `Notify::confirm()`

```php
public static function confirm($token)
```

Confirms an address from its link: the user id, or null when the link is unknown, used or expired

**Parameters**

+ `$token`

Source: [framework/core/Notify.php:255](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L255)

<a name="notify-unsubscribeurl"></a>
### `Notify::unsubscribeUrl()`

```php
public static function unsubscribeUrl($userId)
```

The one-click unsubscribe link of a user's emails (signed with APP_KEY)

**Parameters**

+ `$userId`

Source: [framework/core/Notify.php:269](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L269)

<a name="notify-unsubscribeemail"></a>
### `Notify::unsubscribeEmail()`

```php
public static function unsubscribeEmail($userId, $signature)
```

Turns the user's emails off from a signed link: whether the signature was right

**Parameters**

+ `$userId`
+ `$signature`

Source: [framework/core/Notify.php:277](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L277)

<a name="notify-html"></a>
### `Notify::html()`

```php
public static function html($title, array $paragraphs, $button, $footer, $code = null)
```

An email in the app's look: the colors, font and corners of its design style (DESIGN_STYLE), else Caligrafy's,
written inline since email clients ignore stylesheets. $code: a code to type (shown large), $footer: the last line

**Parameters**

+ `$title`
+ `$paragraphs` `array`
+ `$button`
+ `$footer`
+ `$code`, default `null`

Source: [framework/core/Notify.php:321](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L321)

<a name="notify-theme"></a>
### `Notify::theme()`

```php
public static function theme($public = null)
```

The look of the app's emails: Caligrafy's (public/css/look.css), with the design style of DESIGN_STYLE on top
(public/css/designs/&lt;name&gt;.css): page, canvas, ink, text, muted, border, primary, on_primary, font, radius, card

**Parameters**

+ `$public`, default `null`

Source: [framework/core/Notify.php:353](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L353)

<a name="notify-page"></a>
### `Notify::page()`

```php
public static function page($title, $text, $status = 200)
```

A short page for the links of the emails (Route::notifications)

**Parameters**

+ `$title`
+ `$text`
+ `$status`, default `200`

Source: [framework/core/Notify.php:396](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L396)

<a name="notify-offered"></a>
### `Notify::offered()`

```php
public static function offered()
```

The channels the app offers (NOTIFY_CHANNELS, push,email by default)

Source: [framework/core/Notify.php:413](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L413)

<a name="notify-prefer"></a>
### `Notify::prefer()`

```php
public static function prefer($userId, $channel, $enabled)
```

Turns a channel on or off for a user (a channel without a choice is on)

**Parameters**

+ `$userId`
+ `$channel`
+ `$enabled`

Source: [framework/core/Notify.php:423](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L423)

<a name="notify-enabled"></a>
### `Notify::enabled()`

```php
public static function enabled($userId, $channel)
```

_No doc comment._

**Parameters**

+ `$userId`
+ `$channel`

Source: [framework/core/Notify.php:430](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L430)

<a name="notify-status"></a>
### `Notify::status()`

```php
public static function status($userId)
```

What a user sees about their notifications: the channels, their state and the push public key

**Parameters**

+ `$userId`

Source: [framework/core/Notify.php:439](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L439)

<a name="notify-base"></a>
### `Notify::base()`

```php
public static function base()
```

The app's address, ending with /: APP_URL, else the address of the current web request (null on the command line
without APP_URL)

Source: [framework/core/Notify.php:478](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Notify.php#L478)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Payments -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Payments

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Stripe and cryptocurrency payments.

| Class | What it is |
|---|---|
| [`Caligrafy\Payment`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Payments#payment) | The Payment handles all payment transactions |
| [`Caligrafy\CryptoPayment`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Payments#cryptopayment) | CryptoPayment accepts crypto payments (USDC) through the Coinbase Business Checkouts API. |

<a name="payment"></a>
## class Caligrafy\Payment

```php
namespace Caligrafy;

class Payment extends \stdClass
```

Source: [framework/core/Payment.php:19](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Payment.php#L19)

The Payment handles all payment transactions

### Methods

+ [`->__construct()`](#payment-construct)
+ [`->createTransaction()`](#payment-createtransaction)
+ [`->createPaymentIntent()`](#payment-createpaymentintent)
+ [`->retrieveIntent()`](#payment-retrieveintent)
+ [`->createCheckout()`](#payment-createcheckout)
+ [`->retrieveCheckout()`](#payment-retrievecheckout)
+ [`->createAccount()`](#payment-createaccount)
+ [`->createAccountLink()`](#payment-createaccountlink)
+ [`->createLoginLink()`](#payment-createloginlink)
+ [`->updateAccount()`](#payment-updateaccount)
+ [`->retrieve()`](#payment-retrieve)
+ [`->getPublicKey()`](#payment-getpublickey)

<a name="payment-construct"></a>
#### `->__construct()`

```php
public function __construct()
```

Constructs the Payment Controller to initiate the Stripe api

Source: [framework/core/Payment.php:48](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Payment.php#L48)

<a name="payment-createtransaction"></a>
#### `->createTransaction()`

```php
public function createTransaction(
    $amount,
    $currency,
    $card,
    $receipt_email = null,
    $metadata = null,
    $description = '',
    $transfer = array(),
    $save = false
)
```

Creates a new payment transaction

**Parameters**

+ `$amount` `Integer`: defines the amount of the transaction in cents
+ `$currency` `string`: defines the currecy of the transaction
+ `$card` `Object`: takes the card object submitted
+ `$receipt_email` `string`, default `null`: takes the customer email
+ `$metadata` `string`, default `null`: defines the metadata information that can be passed on to the transaction
+ `$description` `string`, default `''`: defines the description that can be passed on to the transaction
+ `$transfer`, default `array()`
+ `$save` `boolean`, default `false`: defines whether the transaction should be saved or not for a particular customer

**Returns** `$result`: to report on the result of the creation

Source: [framework/core/Payment.php:78](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Payment.php#L78)

<a name="payment-createpaymentintent"></a>
#### `->createPaymentIntent()`

```php
public function createPaymentIntent(
    $amount,
    $currency,
    $metadata = array(),
    $receipt_email = null,
    $description = '',
    $transfer = array()
)
```

Creates a new payment transaction that might require a customer authentication flow (3DSecure for example)

**Parameters**

+ `$amount` `Integer`: defines the amount of the transaction in cents
+ `$currency` `string`: defines the currecy of the transaction
+ `$metadata` `string`, default `array()`: defines the metadata information that can be passed on to the transaction
+ `$receipt_email` `string`, default `null`: defines the email address where the receipt should be sent
+ `$description` `string`, default `''`: defines a description of the product beind sold
+ `$transfer` `array`, default `array()`: defines the transfer data to vendors if they  exist. keys possible: 'destination' for connected stripe account. 'amount' to define the amount the vendor will receive

**Returns** `$result`: to report on the result of the creation

Source: [framework/core/Payment.php:124](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Payment.php#L124)

<a name="payment-retrieveintent"></a>
#### `->retrieveIntent()`

```php
public function retrieveIntent($intentId)
```

Retrieve Payment Intent

**Parameters**

+ `$intentId` `string`

**Returns** `$result`: to report on the result of the creation

Source: [framework/core/Payment.php:158](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Payment.php#L158)

<a name="payment-createcheckout"></a>
#### `->createCheckout()`

```php
public function createCheckout(
    $amount = 1000,
    $currency = 'usd',
    $quantity = 1,
    $productData = array(),
    $successUrl = '',
    $cancelUrl = '',
    $customerEmail = null,
    $locale = null,
    $paymentType = null,
    $payment_intent_data = array(),
    $vendor = array()
)
```

Creates a new integrated checkout session

**Parameters**

+ `$amount` `Integer`, default `1000`: defines the amount of the transaction in cents
+ `$currency` `string`, default `'usd'`: defines the currency of the transaction
+ `$quantity` `string`, default `1`: defines the quantity of products
+ `$productData` `string`, default `array()`: defines the product information that can be passed on to the transaction
+ `$successUrl` `string`, default `''`: defines the url that it will redirect to when successful payment
+ `$cancelUrl` `string`, default `''`: defines the url that it will redirect to when the payment fails
+ `$customerEmail`, default `null`
+ `$locale`, default `null`
+ `$paymentType` `array`, default `null`: defines the different payment methods to be supported by checkout
+ `$payment_intent_data` `array`, default `array()`: . Potential attributes: 'application_fee_amount' for charging vendors
+ `$vendor` `array`, default `array()`: . Potential array keys: 'stripe_account' for the vendor account

**Returns** `$result`: to report on the result of the creation

Source: [framework/core/Payment.php:193](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Payment.php#L193)

<a name="payment-retrievecheckout"></a>
#### `->retrieveCheckout()`

```php
public function retrieveCheckout($sessionId)
```

Retrieve Checkout Session

**Parameters**

+ `$sessionId` `string`

**Returns** `$result`: to report on the result of the creation

Source: [framework/core/Payment.php:256](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Payment.php#L256)

<a name="payment-createaccount"></a>
#### `->createAccount()`

```php
public function createAccount(
    $email = null,
    $country = null,
    $type = 'express',
    $capabilities = array(),
    $accountInformation = array()
)
```

_No doc comment._

**Parameters**

+ `$email`, default `null`
+ `$country`, default `null`
+ `$type`, default `'express'`
+ `$capabilities`, default `array()`
+ `$accountInformation`, default `array()`

Source: [framework/core/Payment.php:283](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Payment.php#L283)

<a name="payment-createaccountlink"></a>
#### `->createAccountLink()`

```php
public function createAccountLink($accountId, $refreshUrl, $returnUrl, $type = 'account_onboarding')
```

_No doc comment._

**Parameters**

+ `$accountId`
+ `$refreshUrl`
+ `$returnUrl`
+ `$type`, default `'account_onboarding'`

Source: [framework/core/Payment.php:314](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Payment.php#L314)

<a name="payment-createloginlink"></a>
#### `->createLoginLink()`

```php
public function createLoginLink($accountId)
```

_No doc comment._

**Parameters**

+ `$accountId`

Source: [framework/core/Payment.php:333](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Payment.php#L333)

<a name="payment-updateaccount"></a>
#### `->updateAccount()`

```php
public function updateAccount($accountId, $updates)
```

_No doc comment._

**Parameters**

+ `$accountId`
+ `$updates`

Source: [framework/core/Payment.php:350](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Payment.php#L350)

<a name="payment-retrieve"></a>
#### `->retrieve()`

```php
public function retrieve($accountId)
```

_No doc comment._

**Parameters**

+ `$accountId`

Source: [framework/core/Payment.php:365](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Payment.php#L365)

<a name="payment-getpublickey"></a>
#### `->getPublicKey()`

```php
public function getPublicKey()
```

Accessor that returns the public key

Source: [framework/core/Payment.php:386](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Payment.php#L386)

<a name="cryptopayment"></a>
## class Caligrafy\CryptoPayment

```php
namespace Caligrafy;

class CryptoPayment extends \stdClass
```

Source: [framework/core/CryptoPayment.php:26](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/CryptoPayment.php#L26)

CryptoPayment accepts crypto payments (USDC) through the Coinbase Business Checkouts API.

Coinbase Commerce (api.commerce.coinbase.com, CRYPTO_PAY_KEY) shut down on March 31, 2026. Its successor is the
Checkouts API of Coinbase Business (https://business.coinbase.com/api/v1/checkouts), available to merchants in the
supported countries. Requests are authenticated with a short-lived JWT signed with a CDP API key:

- COINBASE_API_KEY_NAME: the key name, e.g. organizations/{org_id}/apiKeys/{key_id}
- COINBASE_API_KEY_SECRET: the Ed25519 secret (base64) or the ECDSA private key (PEM, legacy keys)

### Methods

+ [`->__construct()`](#cryptopayment-construct)
+ [`->createTransaction()`](#cryptopayment-createtransaction)
+ [`->cancelTransaction()`](#cryptopayment-canceltransaction)
+ [`->refundTransaction()`](#cryptopayment-refundtransaction)
+ [`->getCharges()`](#cryptopayment-getcharges)
+ [`->getCharge()`](#cryptopayment-getcharge)
+ [`->getChargeStatus()`](#cryptopayment-getchargestatus)
+ [`->coinbaseRequest()`](#cryptopayment-coinbaserequest)
+ [`->jwt()`](#cryptopayment-jwt)

<a name="cryptopayment-construct"></a>
#### `->__construct()`

```php
public function __construct($keyName = null, $keySecret = null)
```

**Parameters**

+ `$keyName` `string`, default `null`: CDP API key name (defaults to COINBASE_API_KEY_NAME)
+ `$keySecret` `string`, default `null`: CDP API key secret (defaults to COINBASE_API_KEY_SECRET)

Source: [framework/core/CryptoPayment.php:53](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/CryptoPayment.php#L53)

<a name="cryptopayment-createtransaction"></a>
#### `->createTransaction()`

```php
public function createTransaction(
    $amount,
    $currency,
    $charge = array(),
    $metadata = array(),
    $redirectUrl = '',
    $cancelUrl = '',
    $expiresAt = null
)
```

Creates a hosted checkout (single-use payment page)

**Parameters**

+ `$amount` `string|float`: the amount (2 decimals at most)
+ `$currency` `string`: USDC or a fiat currency (USD, EUR, GBP, SGD...) converted to USDC at creation
+ `$charge` `array`, default `array()`: 'name' and 'description' of the product
+ `$metadata` `array`, default `array()`: up to 20 string pairs
+ `$redirectUrl` `string`, default `''`: HTTPS URL to come back to after a successful payment
+ `$cancelUrl` `string`, default `''`: HTTPS URL to come back to after a failed payment
+ `$expiresAt` `string`, default `null`: RFC 3339 expiration date (default: 24 hours)

**Returns** `array`: ['action_success' =&gt; bool, 'url' =&gt; hosted payment page, 'data' =&gt; checkout (data['hosted_url'] kept for older code)]

Source: [framework/core/CryptoPayment.php:72](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/CryptoPayment.php#L72)

<a name="cryptopayment-canceltransaction"></a>
#### `->cancelTransaction()`

```php
public function cancelTransaction($id)
```

Deactivates an active checkout so that it can no longer be paid

**Parameters**

+ `$id`

Source: [framework/core/CryptoPayment.php:96](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/CryptoPayment.php#L96)

<a name="cryptopayment-refundtransaction"></a>
#### `->refundTransaction()`

```php
public function refundTransaction($id, $amount = null, $currency = 'USDC', $reason = '')
```

Refunds a completed checkout (full refund when $amount is null)

**Parameters**

+ `$id`
+ `$amount`, default `null`
+ `$currency`, default `'USDC'`
+ `$reason`, default `''`

Source: [framework/core/CryptoPayment.php:104](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/CryptoPayment.php#L104)

<a name="cryptopayment-getcharges"></a>
#### `->getCharges()`

```php
public function getCharges($filters = array())
```

Lists the checkouts. $filters: status, startTime, endTime, descriptionQuery, pageSize, pageToken

**Parameters**

+ `$filters`, default `array()`

Source: [framework/core/CryptoPayment.php:115](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/CryptoPayment.php#L115)

<a name="cryptopayment-getcharge"></a>
#### `->getCharge()`

```php
public function getCharge($chargeId)
```

Retrieves a checkout by id

**Parameters**

+ `$chargeId`

Source: [framework/core/CryptoPayment.php:124](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/CryptoPayment.php#L124)

<a name="cryptopayment-getchargestatus"></a>
#### `->getChargeStatus()`

```php
public function getChargeStatus($chargeId)
```

Returns the status of a checkout: ACTIVE, PROCESSING, COMPLETED, EXPIRED, FAILED, DEACTIVATED, REFUNDED,
PARTIALLY_REFUNDED, or 'unknown'

**Parameters**

+ `$chargeId`

Source: [framework/core/CryptoPayment.php:133](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/CryptoPayment.php#L133)

<a name="cryptopayment-coinbaserequest"></a>
#### `->coinbaseRequest()`

```php
public function coinbaseRequest($requestPath, $requestMethod, $body = null, $additionalHeaders = array())
```

Sends an authenticated request to the Checkouts API

**Parameters**

+ `$requestPath`
+ `$requestMethod`
+ `$body`, default `null`
+ `$additionalHeaders`, default `array()`

**Returns** `array`: ['action_success' =&gt; bool, 'data' =&gt; decoded response] or ['action_success' =&gt; false, 'error' =&gt; message]

Source: [framework/core/CryptoPayment.php:143](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/CryptoPayment.php#L143)

<a name="cryptopayment-jwt"></a>
#### `->jwt()`

```php
public function jwt($method, $path)
```

Builds the JWT that authenticates one request (valid 120 seconds)
Ed25519 keys (base64, 64 bytes) are signed with EdDSA, PEM EC keys with ES256

**Parameters**

+ `$method`
+ `$path`

Source: [framework/core/CryptoPayment.php:169](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/CryptoPayment.php#L169)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-AI -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# AI

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

OpenAI, open models through OpenAI-compatible providers, the OpenAI Assistants and Watson.

| Class | What it is |
|---|---|
| [`Caligrafy\OpenAI`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AI#openai) | The OpenAI class handles all exchanges with the OpenAI models (text and images) |
| [`Caligrafy\Agent`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AI#agent) | The Agent class talks to open models through OpenAI-compatible providers: Groq (default, through groq-php), Together AI, Fireworks AI, OpenRouter, a local Ollama or any custom endpoint. |
| [`Caligrafy\Assistant`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AI#assistant) | The Assistant class runs conversations with OpenAI models through the Responses and Conversations APIs. |
| [`Caligrafy\Watson`](https://github.com/caligrafy/caligrafy-quill/wiki/API-AI#watson) | The Watson class handles all exchanges with the Watson Assistant |

<a name="openai"></a>
## class Caligrafy\OpenAI

```php
namespace Caligrafy;

class OpenAI extends \stdClass
```

Source: [framework/core/OpenAI.php:22](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/OpenAI.php#L22)

The OpenAI class handles all exchanges with the OpenAI models (text and images)

### Constants

+ `COMMANDS = array('CONVERSE', 'SUMMARIZE', 'ANALYZE', 'CORRECT', 'CLASSIFY', 'COMPLETE', 'PREDICT', 'RECOMMEND', 'CUSTOM')`: Commands that delegate() accepts, by name (case insensitive)
+ `TYPES = array('TEXT', 'IMAGE')`: Model types that the constructor accepts, by name (case insensitive)

### Public properties

+ `public $type`: string the OpenAI model type: text or image
+ `public $parameters`: string the OpenAI  model parameters
+ `public $context`: array conversation context
+ `public $attachments`: string the OpenAI file attachments necessary for fine-tuning models

### Methods

+ [`OpenAI::command()`](#openai-command)
+ [`OpenAI::type()`](#openai-type)
+ [`->__construct()`](#openai-construct)
+ [`->converse()`](#openai-converse)
+ [`->delegate()`](#openai-delegate)

<a name="openai-command"></a>
#### `OpenAI::command()`

```php
public static function command($name)
```

Resolves a command name (ex: 'summarize' from a form) to its prompt. Returns null for anything else,
so that user input can never select another constant (such as APP_KEY or DB_PASSWORD)

**Parameters**

+ `$name`

Source: [framework/core/OpenAI.php:38](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/OpenAI.php#L38)

<a name="openai-type"></a>
#### `OpenAI::type()`

```php
public static function type($name)
```

Resolves a model type name ('text' or 'image') to its configuration. Returns null for anything else

**Parameters**

+ `$name`

Source: [framework/core/OpenAI.php:47](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/OpenAI.php#L47)

<a name="openai-construct"></a>
#### `->__construct()`

```php
public function __construct($mode = TEXT)
```

_No doc comment._

**Parameters**

+ `$mode`, default `TEXT`

Source: [framework/core/OpenAI.php:87](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/OpenAI.php#L87)

<a name="openai-converse"></a>
#### `->converse()`

```php
public function converse(
    $parameters = array(),
    $attachments = array(),
    $method = 'POST',
    $additionalHeaders = array()
)
```

General method to command the AI to converse in text
parameters:

- For type text: array of model, prompt/input, instructions, temperature, tokens, max_tokens, top_p, frequency_penalty
- For type image: array of prompt, n, size

attachments:

- For type image: array("image" =&gt; uri to image)

method: POST, GET, PUT, DELETE. default is POST
additionalHeaders: array of request headers to complement default

**Parameters**

+ `$parameters`, default `array()`
+ `$attachments`, default `array()`
+ `$method`, default `'POST'`
+ `$additionalHeaders`, default `array()`

Source: [framework/core/OpenAI.php:109](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/OpenAI.php#L109)

<a name="openai-delegate"></a>
#### `->delegate()`

```php
public function delegate(
    $input = '',
    $outcome = '',
    $command = ANALYZE,
    $context = array(),
    $parameters = array()
)
```

_No doc comment._

**Parameters**

+ `$input`, default `''`
+ `$outcome`, default `''`
+ `$command`, default `ANALYZE`
+ `$context`, default `array()`
+ `$parameters`, default `array()`

Source: [framework/core/OpenAI.php:115](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/OpenAI.php#L115)

<a name="agent"></a>
## class Caligrafy\Agent

```php
namespace Caligrafy;

class Agent extends \stdClass
```

Source: [framework/core/Agent.php:33](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Agent.php#L33)

The Agent class talks to open models through OpenAI-compatible providers:
Groq (default, through groq-php), Together AI, Fireworks AI, OpenRouter, a local Ollama or any custom endpoint.

Choose the provider in .env with AGENT_PROVIDER (groq|together|fireworks|openrouter|ollama|custom).
Key: the provider key (GROQ_API_KEY, TOGETHER_API_KEY, FIREWORKS_API_KEY, OPENROUTER_API_KEY) or AGENT_API_KEY.
AGENT_API_BASE overrides the endpoint (required for custom), AGENT_MODEL and AGENT_VISION_MODEL the default models.
The GROQ_* settings and constants keep working as before.

Groq keeps groq-php: its audio endpoints (multipart uploads) and behavior stay unchanged. The other providers
only need chat completions and the model list, sent with cURL (no extra dependency).

### Constants

+ `PROVIDERS = ...`: Providers: label, default endpoint, key setting, default models (October 2026), audio support, where to get a key and where the models are listed. Ollama needs no key; custom needs AGENT_API_BASE and AGENT_MODEL. Serverless Llama (October 2026): OpenRouter and Ollama only. Groq retired its Llama chat models in August 2026, Together and Fireworks only serve Llama on dedicated/on-demand deployments: their defaults are gpt-oss-120b. Preview models: Groq qwen/qwen3.8-27b.
+ `TIMEOUT = 120`

### Methods

+ [`->__construct()`](#agent-construct)
+ [`Agent::settings()`](#agent-settings)
+ [`Agent::setting()`](#agent-setting)
+ [`->provider()`](#agent-provider)
+ [`->model()`](#agent-model)
+ [`->visionModel()`](#agent-visionmodel)
+ [`->configure()`](#agent-configure)
+ [`->delegate()`](#agent-delegate)
+ [`->visualize()`](#agent-visualize)
+ [`->transcribe()`](#agent-transcribe)
+ [`->translate()`](#agent-translate)
+ [`->models()`](#agent-models)
+ [`Agent::modelIds()`](#agent-modelids)

<a name="agent-construct"></a>
#### `->__construct()`

```php
public function __construct($apiKey = "", $provider = "", $baseUrl = "")
```

apiKey: optional key, otherwise taken from .env
provider: optional provider name, otherwise AGENT_PROVIDER (default groq)
baseUrl: optional endpoint, otherwise AGENT_API_BASE or the provider default

**Parameters**

+ `$apiKey`, default `""`
+ `$provider`, default `""`
+ `$baseUrl`, default `""`

Source: [framework/core/Agent.php:92](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Agent.php#L92)

<a name="agent-settings"></a>
#### `Agent::settings()`

```php
public static function settings($get = null, $provider = "", $baseUrl = "")
```

Resolves the provider settings from .env (or from $get, a function that returns a setting by name: used by doctor)

**Parameters**

+ `$get`, default `null`
+ `$provider`, default `""`
+ `$baseUrl`, default `""`

**Returns** `array`: provider, label, base, baseOverride, key, keyName, model, vision

Source: [framework/core/Agent.php:118](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Agent.php#L118)

<a name="agent-setting"></a>
#### `Agent::setting()`

```php
public static function setting($name)
```

Reads a setting: $_ENV (filled from .env), then the constant of the same name, then getenv()

**Parameters**

+ `$name`

Source: [framework/core/Agent.php:147](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Agent.php#L147)

<a name="agent-provider"></a>
#### `->provider()`

```php
public function provider()
```

Provider in use (groq, together, fireworks, openrouter, ollama or custom)

Source: [framework/core/Agent.php:156](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Agent.php#L156)

<a name="agent-model"></a>
#### `->model()`

```php
public function model()
```

Default text model of the provider (AGENT_MODEL, GROQ_MODEL for Groq, or the built-in default)

Source: [framework/core/Agent.php:164](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Agent.php#L164)

<a name="agent-visionmodel"></a>
#### `->visionModel()`

```php
public function visionModel()
```

Default vision model of the provider (AGENT_VISION_MODEL, GROQ_VISION_MODEL for Groq, or the built-in default)

Source: [framework/core/Agent.php:172](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Agent.php#L172)

<a name="agent-configure"></a>
#### `->configure()`

```php
public function configure($parameters = array())
```

Set configuration of Agent
parameters include: temperature, max_tokens etc. They are added to every delegate() and visualize() request.

**Parameters**

+ `$parameters`, default `array()`

Source: [framework/core/Agent.php:181](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Agent.php#L181)

<a name="agent-delegate"></a>
#### `->delegate()`

```php
public function delegate(
    $model = "",
    $messages = array(),
    $response_format = array(),
    $stream = false,
    $tool_choice = "",
    $tools = array()
)
```

Create a text prompt for agent
model: specify the model of the provider (default: model())
messages: array of role (system, user) and content
response_format: array of types  i.e ['type' =&gt; 'json_object']
stream: set to true if streaming response is expected. Check documentation for fetching results
tool_choice: set to "auto" when tools are used
tools: array of tool definition (OpenAI format)

**Parameters**

+ `$model`, default `""`
+ `$messages`, default `array()`
+ `$response_format`, default `array()`
+ `$stream`, default `false`
+ `$tool_choice`, default `""`
+ `$tools`, default `array()`

Source: [framework/core/Agent.php:196](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Agent.php#L196)

<a name="agent-visualize"></a>
#### `->visualize()`

```php
public function visualize($file = "", $prompt = "Describe this image", $model = "")
```

Vision
file: file path (or a public image URL that the provider downloads)
prompt: what to do with image
model: a vision model of the provider (default: visionModel())

**Parameters**

+ `$file`, default `""`
+ `$prompt`, default `"Describe this image"`
+ `$model`, default `""`

Source: [framework/core/Agent.php:246](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Agent.php#L246)

<a name="agent-transcribe"></a>
#### `->transcribe()`

```php
public function transcribe(
    $file = "",
    $prompt = "",
    $model = GROQ_TRANSCRIPTION_MODEL,
    $language = "en",
    $response_format = "json"
)
```

Audio Transcribe (Groq only)
file: file path
model: specify model to use
response_format: string. 'json'
language: specify language of audio
prompt: string of an optional transcription prompt

**Parameters**

+ `$file`, default `""`
+ `$prompt`, default `""`
+ `$model`, default `GROQ_TRANSCRIPTION_MODEL`
+ `$language`, default `"en"`
+ `$response_format`, default `"json"`

Source: [framework/core/Agent.php:283](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Agent.php#L283)

<a name="agent-translate"></a>
#### `->translate()`

```php
public function translate(
    $file = "",
    $prompt = "",
    $model = GROQ_TRANSCRIPTION_MODEL,
    $response_format = "json"
)
```

Audio Translate (Groq only)
file: file path
model: specify model to use
response_format: string. 'json'
prompt: string of an optional transcription prompt

**Parameters**

+ `$file`, default `""`
+ `$prompt`, default `""`
+ `$model`, default `GROQ_TRANSCRIPTION_MODEL`
+ `$response_format`, default `"json"`

Source: [framework/core/Agent.php:304](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Agent.php#L304)

<a name="agent-models"></a>
#### `->models()`

```php
public function models()
```

Models of the provider (for Ollama: the models pulled on the server)

**Returns** `array`: ['api_success' =&gt; true, 'response' =&gt; sorted list of model ids] or ['api_success' =&gt; false, 'response' =&gt; error]

Source: [framework/core/Agent.php:321](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Agent.php#L321)

<a name="agent-modelids"></a>
#### `Agent::modelIds()`

```php
public static function modelIds($json)
```

Model ids of a GET /models answer: {data: [...]} (OpenAI, Groq, OpenRouter, Ollama /v1/models), a bare list (Together),
or {models: [{name}]} (Ollama /api/tags, Fireworks account models). Models marked inactive (Groq) are left out.

**Parameters**

+ `$json`

**Returns** `array|null`: sorted ids, null when the answer is not a model list

Source: [framework/core/Agent.php:336](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Agent.php#L336)

<a name="assistant"></a>
## class Caligrafy\Assistant

```php
namespace Caligrafy;

class Assistant extends \stdClass
```

Source: [framework/core/Assistant.php:29](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Assistant.php#L29)

The Assistant class runs conversations with OpenAI models through the Responses and Conversations APIs.

OpenAI shut down the Assistants API on August 26, 2026. Version 2.0 of this class keeps the same chainable
methods (start, createMessage, run, retrieveResponse, end) on top of the APIs that replace it:

- the assistant (model, instructions, tools) is configuration kept in this object and sent with every response
- a conversation (POST /v1/conversations) replaces the thread
- a response (POST /v1/responses) replaces the run
- files are searched through a vector store (file_search tool)

### Public properties

+ `public $name`: string the name of the assistant (used for the vector store name and metadata)
+ `public $description`: string what the assistant does (local description)
+ `public $instructions`: string the instructions (system prompt) sent with every response
+ `public $tools = array(["type" => "file_search"])`: array the tools: ["type" =&gt; "file_search"] is completed with the vector store, ["type" =&gt; "code_interpreter"] gets an automatic container with the uploaded files
+ `public $file_ids =[]`: array ids of the files uploaded for the assistant
+ `public $file_paths =[]`: array local paths of the files to upload
+ `public $metadata`: array metadata sent with every response (up to 16 string pairs)
+ `public $vector_store_id = ''`: string the vector store that holds the files searched by file_search
+ `public $assistant_id = ''`: string kept for backward compatibility: the Assistants API no longer exists, nothing is created on OpenAI
+ `public $thread_id = ''`: string the active conversation id (conv_...). Kept under its old name for backward compatibility
+ `public $run_id = ''`: string the last response id (resp_...)
+ `public $status = 'queued'`: string the status of the last response: completed, failed, in_progress, queued, incomplete, cancelled
+ `public $messages =[]`: array the messages of the conversation: the user messages added and the assistant messages received. Every message is ['id', 'role', 'content' =&gt; [['type' =&gt; 'input_text'|'output_text', 'text' =&gt; '...']]]
+ `public $response_text = ''`: string the text of the last assistant answer
+ `public $last_response =[]`: array the last raw response returned by OpenAI (useful for errors and usage)

### Methods

+ [`->__construct()`](#assistant-construct)
+ [`->retrieve()`](#assistant-retrieve)
+ [`->delete()`](#assistant-delete)
+ [`->start()`](#assistant-start)
+ [`->end()`](#assistant-end)
+ [`->createMessage()`](#assistant-createmessage)
+ [`->listMessages()`](#assistant-listmessages)
+ [`->run()`](#assistant-run)
+ [`->retrieveResponse()`](#assistant-retrieveresponse)
+ [`->text()`](#assistant-text)
+ [`->uploadAssistantFiles()`](#assistant-uploadassistantfiles)
+ [`->deleteAssistantFile()`](#assistant-deleteassistantfile)

<a name="assistant-construct"></a>
#### `->__construct()`

```php
public function __construct($parameters = array())
```

Configure an assistant
parameters: name, description, instructions, model, tools, metadata, file_paths (uploaded to a new vector store),
file_ids (already uploaded files), vector_store_id (existing vector store)

**Parameters**

+ `$parameters`, default `array()`

Source: [framework/core/Assistant.php:130](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Assistant.php#L130)

<a name="assistant-retrieve"></a>
#### `->retrieve()`

```php
public function retrieve()
```

Kept for backward compatibility: the assistant configuration lives in this object

Source: [framework/core/Assistant.php:154](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Assistant.php#L154)

<a name="assistant-delete"></a>
#### `->delete()`

```php
public function delete()
```

Deletes the vector store created for the assistant (the uploaded files stay in the OpenAI file storage)

Source: [framework/core/Assistant.php:162](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Assistant.php#L162)

<a name="assistant-start"></a>
#### `->start()`

```php
public function start()
```

Start the contextual conversation (POST /v1/conversations)

Source: [framework/core/Assistant.php:177](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Assistant.php#L177)

<a name="assistant-end"></a>
#### `->end()`

```php
public function end()
```

Delete the contextual conversation

Source: [framework/core/Assistant.php:189](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Assistant.php#L189)

<a name="assistant-createmessage"></a>
#### `->createMessage()`

```php
public function createMessage($content, $file_ids =[], $metadata = null, $role = "user")
```

Add a message to send with the next run()
$file_ids: files given to the code interpreter for this message

**Parameters**

+ `$content`
+ `$file_ids`, default `[]`
+ `$metadata`, default `null`
+ `$role`, default `"user"`

Source: [framework/core/Assistant.php:203](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Assistant.php#L203)

<a name="assistant-listmessages"></a>
#### `->listMessages()`

```php
public function listMessages()
```

Lists the items of the conversation (GET /v1/conversations/{id}/items), oldest first

Source: [framework/core/Assistant.php:217](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Assistant.php#L217)

<a name="assistant-run"></a>
#### `->run()`

```php
public function run(
    $additional_instructions = '',
    $instructions = null,
    $tools =[],
    $model = '',
    $metadata = null
)
```

Send the pending messages and get the answer (POST /v1/responses)
The overrides apply to this response only

**Parameters**

+ `$additional_instructions`, default `''`
+ `$instructions`, default `null`
+ `$tools`, default `[]`
+ `$model`, default `''`
+ `$metadata`, default `null`

Source: [framework/core/Assistant.php:226](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Assistant.php#L226)

<a name="assistant-retrieveresponse"></a>
#### `->retrieveResponse()`

```php
public function retrieveResponse($timeout = 120, $interval = 2)
```

Waits for the last response when it is still queued or in progress (background responses),
polling GET /v1/responses/{id} every $interval seconds for at most $timeout seconds

**Parameters**

+ `$timeout`, default `120`
+ `$interval`, default `2`

Source: [framework/core/Assistant.php:256](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Assistant.php#L256)

<a name="assistant-text"></a>
#### `->text()`

```php
public function text()
```

Returns the text of the last assistant answer

Source: [framework/core/Assistant.php:272](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Assistant.php#L272)

<a name="assistant-uploadassistantfiles"></a>
#### `->uploadAssistantFiles()`

```php
public function uploadAssistantFiles($specified_paths =[])
```

Uploads files (POST /v1/files) and adds them to the assistant's vector store for file_search

**Parameters**

+ `$specified_paths`, default `[]`

**Returns** `array`: the ids of the uploaded files

Source: [framework/core/Assistant.php:281](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Assistant.php#L281)

<a name="assistant-deleteassistantfile"></a>
#### `->deleteAssistantFile()`

```php
public function deleteAssistantFile($file_id)
```

Removes a file from the vector store and deletes it from the OpenAI file storage

**Parameters**

+ `$file_id`

Source: [framework/core/Assistant.php:303](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Assistant.php#L303)

<a name="watson"></a>
## class Caligrafy\Watson

```php
namespace Caligrafy;

class Watson extends \stdClass
```

Source: [framework/core/Watson.php:20](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Watson.php#L20)

The Watson class handles all exchanges with the Watson Assistant

### Methods

+ [`->__construct()`](#watson-construct)
+ [`->communicate()`](#watson-communicate)
+ [`->getSessionId()`](#watson-getsessionid)
+ [`->getContext()`](#watson-getcontext)
+ [`->getSkillVariables()`](#watson-getskillvariables)
+ [`->getContextVariable()`](#watson-getcontextvariable)
+ [`->getConversation()`](#watson-getconversation)
+ [`->getLastExchange()`](#watson-getlastexchange)
+ [`->getResponse()`](#watson-getresponse)
+ [`->getExchangeAt()`](#watson-getexchangeat)
+ [`->closeSession()`](#watson-closesession)

<a name="watson-construct"></a>
#### `->__construct()`

```php
public function __construct($watson_assistant_id, $environment_id = null)
```

.env settings:

- WATSON_API_KEY: the service API key
- WATSON_URL: the service instance URL, https://api.&lt;region&gt;.assistant.watson.cloud.ibm.com/instances/&lt;instance_id&gt;
- WATSON_ENVIRONMENT_ID (optional): the environment of the assistant (Environment settings &gt; API details). Without it, the legacy /v2/assistants/&lt;id&gt;/sessions path is used
- WATSON_API_VERSION (optional): the API version date, 2024-08-25 by default

**Parameters**

+ `$watson_assistant_id`
+ `$environment_id`, default `null`

Source: [framework/core/Watson.php:90](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Watson.php#L90)

<a name="watson-communicate"></a>
#### `->communicate()`

```php
public function communicate($messageText, $skillVariables = null)
```

Send Input to Watson

**Parameters**

+ `$messageText` `string`: to send to Watson
+ `$skillVariables` `array`, default `null`

Source: [framework/core/Watson.php:124](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Watson.php#L124)

<a name="watson-getsessionid"></a>
#### `->getSessionId()`

```php
public function getSessionId()
```

Get Session ID

**Returns** `the`: current active session ID

Source: [framework/core/Watson.php:157](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Watson.php#L157)

<a name="watson-getcontext"></a>
#### `->getContext()`

```php
public function getContext()
```

Get Context

**Returns** `the`: current Context

Source: [framework/core/Watson.php:170](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Watson.php#L170)

<a name="watson-getskillvariables"></a>
#### `->getSkillVariables()`

```php
public function getSkillVariables()
```

Get Skill Variables

**Returns** `the`: skill variables

Source: [framework/core/Watson.php:182](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Watson.php#L182)

<a name="watson-getcontextvariable"></a>
#### `->getContextVariable()`

```php
public function getContextVariable($variable)
```

Get Context Variable

**Parameters**

+ `$variable`

**Returns** `the`: Context variable

Source: [framework/core/Watson.php:196](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Watson.php#L196)

<a name="watson-getconversation"></a>
#### `->getConversation()`

```php
public function getConversation()
```

Get Context

**Returns** `the`: current Conversation

Source: [framework/core/Watson.php:210](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Watson.php#L210)

<a name="watson-getlastexchange"></a>
#### `->getLastExchange()`

```php
public function getLastExchange()
```

Get Context

**Returns** `the`: last exchange

Source: [framework/core/Watson.php:223](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Watson.php#L223)

<a name="watson-getresponse"></a>
#### `->getResponse()`

```php
public function getResponse()
```

Get Last Response

**Returns** `the`: last response

Source: [framework/core/Watson.php:236](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Watson.php#L236)

<a name="watson-getexchangeat"></a>
#### `->getExchangeAt()`

```php
public function getExchangeAt($turnCount)
```

Get conversation exchange at turn count

**Parameters**

+ `$turnCount` `int`: defines the turn count of the conversation

**Returns** `array`: the conversation exchange at turn count

Source: [framework/core/Watson.php:251](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Watson.php#L251)

<a name="watson-closesession"></a>
#### `->closeSession()`

```php
public function closeSession()
```

Close the Watson Session

**Returns** `boolean`: true if session closed successfully

Source: [framework/core/Watson.php:265](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Watson.php#L265)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Interfaces: REST, the JS client and MCP

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

The channels that serve the capabilities besides web pages.

| Class | What it is |
|---|---|
| [`Caligrafy\Rest`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#rest) | Answers HTTP requests with capabilities, in JSON: - Route::capability('POST', '/books', 'create_book') maps one route to one capability - Route::capabilities('/capabilities') adds GET /capabilities (what the caller may ... |
| [`Caligrafy\Client`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#client) | One ES module, no dependency, for the Vue apps, the Vite SPA and Node scripts: one async function per capability (create_book becomes createBook) plus call(name, input) and capabilities(). |
| [`Caligrafy\Mcp\Http`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#mcp-http) | One JSON-RPC message per POST, answered with application/json (no event stream: every tool answers at once). |
| [`Caligrafy\Mcp\Server`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#mcp-server) | JSON-RPC 2.0 messages of MCP, independent of the transport (Http for Streamable HTTP, caligrafer mcp for stdio): initialize, ping, tools/list, tools/call; notifications get no answer. |
| [`Caligrafy\Async\Kernel`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#async-kernel) | What the async server runs, whatever server it is: boot() once per process (settings, constants, the class map, the application's config and container, the capabilities), then handle() for each request, one at a time ... |
| [`Caligrafy\Async\Eligibility`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#async-eligibility) | The async server keeps the application in memory and answers many requests from one process, so a capability it runs must not keep anything from one caller to the next, nor talk to the web server's request directly. |
| [`Caligrafy\Async\WorkermanServer`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#async-workermanserver) | Workerman (pure PHP, composer require workerman/workerman: php caligrafer.php add async) keeps a few processes that each hold the application in memory (Kernel::boot) and many open connections, answering one request at ... |

<a name="rest"></a>
## class Caligrafy\Rest

```php
namespace Caligrafy;

class Rest
```

Source: [framework/interfaces/Rest.php:25](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Rest.php#L25)

Class Rest
Answers HTTP requests with capabilities, in JSON:

- Route::capability('POST', '/books', 'create_book') maps one route to one capability
- Route::capabilities('/capabilities') adds GET /capabilities (what the caller may call, with the input schemas, and the CSRF token of the session in "csrf") and POST /capabilities/{name} (call any capability by name: the JS client of the Vue apps uses it)

Who calls: a personal access token (Authorization: Bearer cq_...), the legacy API key, or the signed-in user. Calls
made with the session cookie need the CSRF token in an X-CSRF-Token header (or \_token) unless they only read.
Inputs: the JSON body (or form fields, or the query string for GET), then the route variables, which win.
Responses: 200 with the result ({"data": ...}), 201 when a POST creates, or {"error": {"code", "message", "fields"}}
with 401, 403, 404, 409 or 422.

### Methods

+ [`Rest::respond()`](#rest-respond)
+ [`Rest::answer()`](#rest-answer)
+ [`Rest::listing()`](#rest-listing)
+ [`Rest::input()`](#rest-input)

<a name="rest-respond"></a>
#### `Rest::respond()`

```php
public static function respond($name, $request = null)
```

Runs a capability for the current request and prints the response

**Parameters**

+ `$name`
+ `$request`, default `null`

Source: [framework/interfaces/Rest.php:30](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Rest.php#L30)

<a name="rest-answer"></a>
#### `Rest::answer()`

```php
public static function answer(
    $name,
    callable $context,
    callable $input,
    $method = 'POST',
    ?callable $csrf = null,
    ?Uploads $uploads = null
)
```

The answer to a call of a capability, without printing it (2.26.0: the web server prints it, the async server
sends it): ['status' =&gt; 200|201|4xx, 'body' =&gt; ['data' =&gt; ...] or ['error' =&gt; ...]]

**Parameters**

+ `$name`
+ `$context` `callable`: returns the caller's Context
+ `$input` `callable`: returns the inputs
+ `$method` `string`, default `'POST'`: the HTTP method (a POST that creates answers 201)
+ `$csrf` `?callable`, default `null`: returns false when a session caller's write lacks its CSRF token
+ `$uploads` `?Uploads`, default `null`

Source: [framework/interfaces/Rest.php:59](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Rest.php#L59)

<a name="rest-listing"></a>
#### `Rest::listing()`

```php
public static function listing($request = null)
```

GET {prefix}: the capabilities the caller may call

**Parameters**

+ `$request`, default `null`

Source: [framework/interfaces/Rest.php:82](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Rest.php#L82)

<a name="rest-input"></a>
#### `Rest::input()`

```php
public static function input($request)
```

The inputs: body or query string, then the route variables

**Parameters**

+ `$request`

Source: [framework/interfaces/Rest.php:93](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Rest.php#L93)

<a name="client"></a>
## class Caligrafy\Client

```php
namespace Caligrafy;

class Client
```

Source: [framework/interfaces/Client.php:19](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Client.php#L19)

Class Client
One ES module, no dependency, for the Vue apps, the Vite SPA and Node scripts: one async function per capability
(create_book becomes createBook) plus call(name, input) and capabilities(). It talks to Route::capabilities().

- In a page of the application it uses the session: the cookie, and the CSRF token it reads once from GET {prefix}. Elsewhere (Node, another origin) configure({ baseUrl, token }) sends a personal access token.
- A refused call throws CapabilityError with status, code (invalid, forbidden...), message and fields.

### Methods

+ [`Client::generate()`](#client-generate)
+ [`Client::camel()`](#client-camel)

<a name="client-generate"></a>
#### `Client::generate()`

```php
public static function generate($prefix = '/capabilities')
```

The source of the module

**Parameters**

+ `$prefix` `string`, default `'/capabilities'`: the uri of Route::capabilities()

Source: [framework/interfaces/Client.php:25](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Client.php#L25)

<a name="client-camel"></a>
#### `Client::camel()`

```php
public static function camel($name)
```

create_book -&gt; createBook

**Parameters**

+ `$name`

Source: [framework/interfaces/Client.php:107](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Client.php#L107)

<a name="mcp-http"></a>
## class Caligrafy\Mcp\Http

```php
namespace Caligrafy\Mcp;

class Http
```

Source: [framework/interfaces/Mcp/Http.php:22](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Mcp/Http.php#L22)

Class Http
One JSON-RPC message per POST, answered with application/json (no event stream: every tool answers at once).

- Authentication: Authorization: Bearer &lt;personal access token&gt;. Without a valid token: 401 with WWW-Authenticate.
- Origin: a browser request from another site is refused (403), against DNS rebinding. Allowed: no Origin header (agents), the application's own host, and the origins listed in MCP_ALLOWED_ORIGINS (comma separated).
- Notifications are answered 202 with no body. GET and DELETE answer 405 (no server-initiated stream, no sessions).

### Methods

+ [`Http::respond()`](#mcp-http-respond)
+ [`Http::methodNotAllowed()`](#mcp-http-methodnotallowed)
+ [`Http::originAllowed()`](#mcp-http-originallowed)

<a name="mcp-http-respond"></a>
#### `Http::respond()`

```php
public static function respond()
```

_No doc comment._

Source: [framework/interfaces/Mcp/Http.php:24](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Mcp/Http.php#L24)

<a name="mcp-http-methodnotallowed"></a>
#### `Http::methodNotAllowed()`

```php
public static function methodNotAllowed()
```

_No doc comment._

Source: [framework/interfaces/Mcp/Http.php:51](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Mcp/Http.php#L51)

<a name="mcp-http-originallowed"></a>
#### `Http::originAllowed()`

```php
public static function originAllowed($origin, $host)
```

Whether a browser Origin may call the endpoint

**Parameters**

+ `$origin`
+ `$host`

Source: [framework/interfaces/Mcp/Http.php:62](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Mcp/Http.php#L62)

<a name="mcp-server"></a>
## class Caligrafy\Mcp\Server

```php
namespace Caligrafy\Mcp;

class Server
```

Source: [framework/interfaces/Mcp/Server.php:26](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Mcp/Server.php#L26)

Class Server
JSON-RPC 2.0 messages of MCP, independent of the transport (Http for Streamable HTTP, caligrafer mcp for stdio):
initialize, ping, tools/list, tools/call; notifications get no answer.

The tools are the capabilities the context may call, with their input schema and the hints agents use to decide
when to ask the user first (readOnlyHint, destructiveHint). A tool call goes through Capabilities::call(): the same
permission checks, validation and audit as every other channel. A refused call (invalid input, forbidden...) is a
tool result with isError, so the agent can read the reason and correct itself; protocol errors are JSON-RPC errors.

### Constants

+ `PROTOCOL_VERSIONS = array('2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05')`
+ `PARSE_ERROR = -32700`
+ `INVALID_REQUEST = -32600`
+ `METHOD_NOT_FOUND = -32601`
+ `INVALID_PARAMS = -32602`
+ `INTERNAL_ERROR = -32603`

### Methods

+ [`->__construct()`](#mcp-server-construct)
+ [`->handleJson()`](#mcp-server-handlejson)
+ [`->handle()`](#mcp-server-handle)
+ [`->tools()`](#mcp-server-tools)
+ [`Server::result()`](#mcp-server-result)
+ [`Server::error()`](#mcp-server-error)

<a name="mcp-server-construct"></a>
#### `->__construct()`

```php
public function __construct(Context $context, $name = null)
```

_No doc comment._

**Parameters**

+ `$context` `Context`
+ `$name`, default `null`

Source: [framework/interfaces/Mcp/Server.php:42](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Mcp/Server.php#L42)

<a name="mcp-server-handlejson"></a>
#### `->handleJson()`

```php
public function handleJson($json)
```

Handles one message (a JSON string)

**Parameters**

+ `$json`

**Returns** `array|null`: the response, or null for a notification

Source: [framework/interfaces/Mcp/Server.php:52](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Mcp/Server.php#L52)

<a name="mcp-server-handle"></a>
#### `->handle()`

```php
public function handle($message)
```

Handles one decoded message

**Parameters**

+ `$message`

**Returns** `array|null`: the response, or null for a notification

Source: [framework/interfaces/Mcp/Server.php:65](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Mcp/Server.php#L65)

<a name="mcp-server-tools"></a>
#### `->tools()`

```php
public function tools()
```

The tools of this context

Source: [framework/interfaces/Mcp/Server.php:101](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Mcp/Server.php#L101)

<a name="mcp-server-result"></a>
#### `Server::result()`

```php
public static function result($id, $result)
```

_No doc comment._

**Parameters**

+ `$id`
+ `$result`

Source: [framework/interfaces/Mcp/Server.php:161](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Mcp/Server.php#L161)

<a name="mcp-server-error"></a>
#### `Server::error()`

```php
public static function error($id, $code, $message)
```

_No doc comment._

**Parameters**

+ `$id`
+ `$code`
+ `$message`

Source: [framework/interfaces/Mcp/Server.php:166](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/interfaces/Mcp/Server.php#L166)

<a name="async-kernel"></a>
## class Caligrafy\Async\Kernel

```php
namespace Caligrafy\Async;

class Kernel
```

Source: [framework/core/Async/Kernel.php:34](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Async/Kernel.php#L34)

Class Kernel
What the async server runs, whatever server it is: boot() once per process (settings, constants, the class map, the
application's config and container, the capabilities), then handle() for each request, one at a time per process.

It answers the capabilities channel only, as Route::capabilities() does on the web server:

```
GET  {prefix}         the capabilities the caller may call
POST {prefix}/{name}  a call (GET too for a read-only capability), inputs in the JSON body or the query string
```

The caller is known from its token (Authorization: Bearer cq_...), or is a visitor. There is no session and no
cookie here: a request that brings the session cookie is the web server's (handles() says so), as is a capability
that Eligibility refuses. Between requests, everything a request may leave behind is forgotten (endRequest()).

### Methods

+ [`Kernel::boot()`](#async-kernel-boot)
+ [`Kernel::handles()`](#async-kernel-handles)
+ [`Kernel::handle()`](#async-kernel-handle)
+ [`Kernel::eligible()`](#async-kernel-eligible)
+ [`Kernel::endRequest()`](#async-kernel-endrequest)

<a name="async-kernel-boot"></a>
#### `Kernel::boot()`

```php
public static function boot($prefix = '/capabilities')
```

Starts the framework once for this process (the root of the project is the current folder)

**Parameters**

+ `$prefix`, default `'/capabilities'`

Source: [framework/core/Async/Kernel.php:43](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Async/Kernel.php#L43)

<a name="async-kernel-handles"></a>
#### `Kernel::handles()`

```php
public static function handles($method, $path, array $cookies = array())
```

Whether this server answers the request: a path of the capabilities channel, no session cookie, and (for a call)
a capability that may run here. Otherwise the web server answers it.

**Parameters**

+ `$method`
+ `$path`
+ `$cookies` `array`, default `array()`

Source: [framework/core/Async/Kernel.php:62](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Async/Kernel.php#L62)

<a name="async-kernel-handle"></a>
#### `Kernel::handle()`

```php
public static function handle($method, $path, array $headers, $body, array $query = array())
```

Answers one request

**Parameters**

+ `$method`
+ `$path`
+ `$headers` `array`: lower-case names
+ `$body`
+ `$query` `array`, default `array()`: the query string's values

**Returns** `array`: ['status' =&gt; int, 'headers' =&gt; [name =&gt; value], 'body' =&gt; string]

Source: [framework/core/Async/Kernel.php:84](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Async/Kernel.php#L84)

<a name="async-kernel-eligible"></a>
#### `Kernel::eligible()`

```php
public static function eligible($name)
```

Whether a capability may run here (Eligibility, decided once per process)

**Parameters**

+ `$name`

Source: [framework/core/Async/Kernel.php:120](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Async/Kernel.php#L120)

<a name="async-kernel-endrequest"></a>
#### `Kernel::endRequest()`

```php
public static function endRequest()
```

Forgets what one request may leave in memory: this request's cache copies, a transaction left open, container
instances, the query watch, the lazy-loading warnings. The database connection stays open for the next request.

Source: [framework/core/Async/Kernel.php:132](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Async/Kernel.php#L132)

<a name="async-eligibility"></a>
## class Caligrafy\Async\Eligibility

```php
namespace Caligrafy\Async;

class Eligibility
```

Source: [framework/core/Async/Eligibility.php:28](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Async/Eligibility.php#L28)

Class Eligibility
The async server keeps the application in memory and answers many requests from one process, so a capability it runs
must not keep anything from one caller to the next, nor talk to the web server's request directly. A capability is
eligible when its class's own source (read as PHP tokens: comments and strings do not count) uses none of:

- the request and the session: $_SESSION, $_COOKIE, $_GET, $_POST, $_REQUEST, $_FILES, $_SERVER, session(), request(), Auth::, redirect(), view() (the async channel knows its caller only from a token, or as a visitor);
- output and the end of the process: echo, print, printf, var_dump, header(), setcookie(), http_response_code(), exit, die, ob_*() (it returns data; the server sends it);
- state kept between calls: global, static variables, assignments to static properties;

and it is not webOnly and takes no file input (the `file` rule).
Anything else (classes it calls) is not read: the isolation test (php caligrafer.php async check) runs each eligible
capability for two callers in one process and compares. A capability that is not eligible is answered by the web
server as before: being unsafe makes it slower, never shared.

### Constants

+ `SUPERGLOBALS = array('$_SESSION', '$_COOKIE', '$_GET', '$_POST', '$_REQUEST', '$_FILES', '$_SERVER', '$GLOBALS')`
+ `FUNCTIONS = ...`

### Methods

+ [`Eligibility::reasons()`](#async-eligibility-reasons)
+ [`Eligibility::eligible()`](#async-eligibility-eligible)
+ [`Eligibility::sourceReasons()`](#async-eligibility-sourcereasons)

<a name="async-eligibility-reasons"></a>
#### `Eligibility::reasons()`

```php
public static function reasons($name)
```

Why a capability cannot run on the async server, or an empty list when it can

**Parameters**

+ `$name`

**Returns** `string[]`: the reasons

Source: [framework/core/Async/Eligibility.php:39](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Async/Eligibility.php#L39)

<a name="async-eligibility-eligible"></a>
#### `Eligibility::eligible()`

```php
public static function eligible($name)
```

Whether a capability can run on the async server

**Parameters**

+ `$name`

Source: [framework/core/Async/Eligibility.php:68](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Async/Eligibility.php#L68)

<a name="async-eligibility-sourcereasons"></a>
#### `Eligibility::sourceReasons()`

```php
public static function sourceReasons($source)
```

What a PHP source uses that the async server cannot allow

**Parameters**

+ `$source`

**Returns** `string[]`: the reasons, at most one per kind

Source: [framework/core/Async/Eligibility.php:77](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Async/Eligibility.php#L77)

<a name="async-workermanserver"></a>
## class Caligrafy\Async\WorkermanServer

```php
namespace Caligrafy\Async;

class WorkermanServer
```

Source: [framework/core/Async/WorkermanServer.php:25](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Async/WorkermanServer.php#L25)

Class WorkermanServer
Workerman (pure PHP, composer require workerman/workerman: php caligrafer.php add async) keeps a few processes
that each hold the application in memory (Kernel::boot) and many open connections, answering one request at a time
per process. In front of the web server (ASYNC=on in the production image: docker/production/start.sh), it answers
the capabilities channel itself (Kernel::handles) and passes every other request, unchanged, to Apache on
127.0.0.1:&lt;backend port&gt;, adding X-Forwarded-For; without a backend (development), others get a 404.

### Methods

+ [`WorkermanServer::run()`](#async-workermanserver-run)

<a name="async-workermanserver-run"></a>
#### `WorkermanServer::run()`

```php
public static function run($listen, $workers, $backend = null, $prefix = '/capabilities')
```

Runs the server (this call does not return)

**Parameters**

+ `$listen` `string`: e.g. http://0.0.0.0:80
+ `$workers` `int`: processes (each holds one copy of the application)
+ `$backend` `string|null`, default `null`: the web server for everything else, e.g. 127.0.0.1:8080
+ `$prefix`, default `'/capabilities'`

Source: [framework/core/Async/WorkermanServer.php:33](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Async/WorkermanServer.php#L33)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Snap

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Snap Cards and the assistant (namespace Caligrafy\Snap): cards built from what capabilities declare, the conversation, the planner and the setup.

| Class | What it is |
|---|---|
| [`Caligrafy\Snap\Cards`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Cards#snap-cards) | Snap Cards (2.23.0): every card is built from what a capability already declares |
| [`Caligrafy\Snap\Hints`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-hints) | Snap Cards work without any hint: every card is built from what a capability declares (its rules, descriptions, readOnly and destructive). |
| [`Caligrafy\Snap\Views`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-views) | How a Show card looks, best first (2.25.0): 1. its card view: application/views/snap/&lt;capability&gt;.pug, a Pug view made for the card, in the app's own markup and |
| [`Caligrafy\Snap\Designer`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-designer) | A capability shown through its own page uses that page (Snap\Views). |
| [`Caligrafy\Snap\Conversation`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Conversation#snap-conversation) | The Snap shell's two spaces (2.23.0) |
| [`Caligrafy\Snap\Planner`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-planner) | The Snap shell's planner (2.23.0): Claude reads what the person typed or said and answers with cards. |
| [`Caligrafy\Snap\Flow`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-flow) | The next card for a capability and its inputs, the same whoever asks (a card that is sent, the shell's fast path, the model's choice): one place decides, so the planner can never take a shortcut around consent. |
| [`Caligrafy\Snap\Input`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-input) | The inputs of a card arrive as an object, or its JSON (agents and addresses send JSON text): this gives the plain values only (a nested object or list is left out: a card's inputs are scalars). |
| [`Caligrafy\Snap\Reads`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-reads) | The reads of one request, once (2.23.0): Home asks the same lists for its alerts, insights and picks; each runs once per person per request. |
| [`Caligrafy\Snap\Say`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-say) | The assistant's line after every action (2.23.0): whatever the person did (sent a form, picked a choice, confirmed, opened a row, undid, saved a shortcut), the answer carries what the assistant says about it, shown in ... |
| [`Caligrafy\Snap\Consent`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-consent) | Snap consent (2.23.0): nothing that changes data runs from a card until the person confirms it. |
| [`Caligrafy\Snap\Offers`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-offers) | Offer: Suggestion and Offer: Routine (2.23.0): the assistant notices what a person does again and again, only if they turned noticing on, and offers to help. |
| [`Caligrafy\Snap\Shortcuts`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-shortcuts) | Go: Shortcut cards (2.23.0): a request a person saved (a capability with its inputs), run with one click. |
| [`Caligrafy\Snap\Tasks`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-tasks) | Track: Task cards (2.23.0): work that runs in the background for one person. |
| [`Caligrafy\Snap\Discover`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-discover) | Discover (2.23.0): Home surfaces the things this application is about, to invite browsing, the way a shop surfaces products. |
| [`Caligrafy\Snap\Setup`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-setup) | install: the tables (framework/settings/platform.sql), a starter application/config/snap.php when there is none, then the two lines to add by hand (they are the app's own files): Route::snap(); in web.php, and the ... |
| [`Caligrafy\Snap\Shell`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-shell) | The Snap shell's fast path (2.23.0): what it can answer without a model, at once and for free |

<a name="snap-cards"></a>
## class Caligrafy\Snap\Cards

Snap Cards (2.23.0): every card is built from what a capability already declares

Its 16 public methods have a page of their own: [Caligrafy\Snap\Cards](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Cards).

<a name="snap-hints"></a>
## class Caligrafy\Snap\Hints

```php
namespace Caligrafy\Snap;

class Hints
```

Source: [framework/core/Snap/Hints.php:30](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Hints.php#L30)

Class Hints
Snap Cards work without any hint: every card is built from what a capability declares (its rules, descriptions,
readOnly and destructive). Hints only make them better, from one file the app owns, application/config/snap.php:

```
return [
    'about' => 'a library app',                       // what the assistant is the assistant of (the planner)
    'cards' => [                                      // keyed by capability name
        'list_books' => ['title' => 'The catalog', 'columns' => ['title', 'author.name'], 'empty' => 'No book yet.'],
        'reading_report' => ['async' => true, 'working' => ['Counting the books…']],
    ],
];
```

A file that returns the cards alone (no 'cards' key) works too. The keys of a card are in the wiki page
"Snap Cards and the Assistant": title, lead, submit, columns, labels, hide, values, choices, open, full, empty,
variant, noun, icon, done, undo, next, applies, empty_next, alert, insight, discover, working, async, consequence,
confirm, card (2.25.0: its card view, 'Folder/view' under application/views, or false), view (2.24.0: the page whose
part marked data-snap shows it, or false) and design (2.24.0: how its data is shown without a card view or a page).
A capability is async when #[Capability(async: true)] says so, or its hint does.

### Methods

+ [`Hints::for()`](#snap-hints-for)
+ [`Hints::about()`](#snap-hints-about)
+ [`Hints::forget()`](#snap-hints-forget)

<a name="snap-hints-for"></a>
#### `Hints::for()`

```php
public static function for($name)
```

The hints of one capability (an empty array when it has none)

**Parameters**

+ `$name`

Source: [framework/core/Snap/Hints.php:37](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Hints.php#L37)

<a name="snap-hints-about"></a>
#### `Hints::about()`

```php
public static function about()
```

What the app is about, for the assistant ("a library app"); empty when the file does not say

Source: [framework/core/Snap/Hints.php:46](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Hints.php#L46)

<a name="snap-hints-forget"></a>
#### `Hints::forget()`

```php
public static function forget()
```

Forgets the file read (tests, and a file that changed)

Source: [framework/core/Snap/Hints.php:54](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Hints.php#L54)

<a name="snap-views"></a>
## class Caligrafy\Snap\Views

```php
namespace Caligrafy\Snap;

class Views
```

Source: [framework/core/Snap/Views.php:25](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Views.php#L25)

Class Views
How a Show card looks, best first (2.25.0):
1. its card view: application/views/snap/&lt;capability&gt;.pug, a Pug view made for the card, in the app's own markup and classes, rendered on the server into the card (the hint 'card' =&gt; 'Folder/view' names another, false none). It gets $result (what the capability returned), $rows and $page for a list, $record for one record, $input, $card, $home, $authorized and $user. A link with data-snap-open="&lt;capability&gt;" and data-snap-input='{"id":7}' opens that card in the conversation. Written by Claude from the app's views (the assistant skill); its first line names the page it was made from and that page's fingerprint, so `php caligrafer.php snap views` says when it is stale.
2. the part of its page marked data-snap="&lt;capability&gt;" (a Route::page whose first data it is), embedded in the card (?snap-embed: no frame, sized to it); a whole page only when the hint 'view' names it
3. a card designed for its data in the app's design system (Snap\Designer)

### Methods

+ [`Views::embed()`](#snap-views-embed)
+ [`Views::page()`](#snap-views-page)
+ [`Views::card()`](#snap-views-card)
+ [`Views::cardFile()`](#snap-views-cardfile)
+ [`Views::source()`](#snap-views-source)
+ [`Views::fingerprint()`](#snap-views-fingerprint)
+ [`Views::cards()`](#snap-views-cards)

<a name="snap-views-embed"></a>
#### `Views::embed()`

```php
public static function embed($name, array $inputs)
```

The address of the page that shows a capability, with its inputs in place, in embed mode; null when there is none
(no page uses it as data, or one of the page's route variables is not among the inputs)

**Parameters**

+ `$name`
+ `$inputs` `array`

Source: [framework/core/Snap/Views.php:31](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Views.php#L31)

<a name="snap-views-page"></a>
#### `Views::page()`

```php
public static function page($html)
```

Renders a page in embed mode: its style sheet and script go in, so the page shows without the site's frame
and tells the card its height

**Parameters**

+ `$html`

Source: [framework/core/Snap/Views.php:97](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Views.php#L97)

<a name="snap-views-card"></a>
#### `Views::card()`

```php
public static function card($name, $result, array $input, array $card = array())
```

The HTML of a capability's card view, or null when it has none (or it failed: the card is then designed)

**Parameters**

+ `$name`
+ `$result` `mixed`: what the capability returned, as plain arrays
+ `$input` `array`
+ `$card` `array`, default `array()`

Source: [framework/core/Snap/Views.php:114](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Views.php#L114)

<a name="snap-views-cardfile"></a>
#### `Views::cardFile()`

```php
public static function cardFile($name)
```

The card view file of a capability, or null: the hint 'card' (a view name, or false), else views/snap/&lt;name&gt;.pug

**Parameters**

+ `$name`

Source: [framework/core/Snap/Views.php:152](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Views.php#L152)

<a name="snap-views-source"></a>
#### `Views::source()`

```php
public static function source($file)
```

What the first line of a card view says it was made from: array('view' =&gt; 'Bookshelf/books', 'print' =&gt; '1a2b3c4d')
(//- snap card of list_books, from Bookshelf/books.pug 1a2b3c4d), or null

**Parameters**

+ `$file`

Source: [framework/core/Snap/Views.php:166](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Views.php#L166)

<a name="snap-views-fingerprint"></a>
#### `Views::fingerprint()`

```php
public static function fingerprint($view)
```

A view's fingerprint, written in the card views made from it: when the view changes, they are stale

**Parameters**

+ `$view`

Source: [framework/core/Snap/Views.php:175](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Views.php#L175)

<a name="snap-views-cards"></a>
#### `Views::cards()`

```php
public static function cards()
```

Every card view of the app, with what it was made from and whether it is stale:
[name =&gt; ['file', 'from', 'stale' (true, false, or null when its first line names no view)]]

Source: [framework/core/Snap/Views.php:185](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Views.php#L185)

<a name="snap-designer"></a>
## class Caligrafy\Snap\Designer

```php
namespace Caligrafy\Snap;

class Designer
```

Source: [framework/core/Snap/Designer.php:23](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Designer.php#L23)

Class Designer
A capability shown through its own page uses that page (Snap\Views). Without one, its card is designed, never dumped:
a design says which of the data makes the title, the line under it, the badges, the numbers that stand out, the
details, the longer text and the tags of a record, or the title, line, details and badge of each row of a list.
The page then draws it with the app's own design tokens (its DESIGN_STYLE), so it looks like the rest of the app.

Who designs it: the hint 'design' of application/config/snap.php when the app gives one; else Claude (when the
assistant has its key), once for each shape of data, kept in the cache; else rules from the names of the fields.

### Constants

+ `FORMATS = array('text', 'number', 'money', 'percent', 'date', 'datetime', 'bool', 'email', 'url')`
+ `TONES = array('success', 'warning', 'danger', 'info', 'neutral')`
+ `CACHE_DAYS = 30`

### Public properties

+ `public static $model = true`: bool false: rules only, never the model (tests, and a design asked for while answering)
+ `public static $transport = null`: Tests fake Claude's design here (a callable that takes the request and returns the response), apart from the planner's: a test that fakes the planner never sees the designer's requests

### Methods

+ [`Designer::record()`](#snap-designer-record)
+ [`Designer::rows()`](#snap-designer-rows)
+ [`Designer::spec()`](#snap-designer-spec)
+ [`Designer::paths()`](#snap-designer-paths)
+ [`Designer::format()`](#snap-designer-format)

<a name="snap-designer-record"></a>
#### `Designer::record()`

```php
public static function record($name, array $record)
```

The blocks of a record's card, values in place and formatted: hero (eyebrow, title, subtitle, badges), stats,
fields, text, tags

**Parameters**

+ `$name`
+ `$record` `array`

Source: [framework/core/Snap/Designer.php:50](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Designer.php#L50)

<a name="snap-designer-rows"></a>
#### `Designer::rows()`

```php
public static function rows($name, array $rows)
```

Each row of a list, designed: title, subtitle, details (meta), a badge

**Parameters**

+ `$name`
+ `$rows` `array`

Source: [framework/core/Snap/Designer.php:89](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Designer.php#L89)

<a name="snap-designer-spec"></a>
#### `Designer::spec()`

```php
public static function spec($name, $kind, array $sample)
```

The design of a capability's data: the app's hint, else Claude's (kept for its shape), else the rules

**Parameters**

+ `$name`
+ `$kind`
+ `$sample` `array`

Source: [framework/core/Snap/Designer.php:116](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Designer.php#L116)

<a name="snap-designer-paths"></a>
#### `Designer::paths()`

```php
public static function paths(array $data, $prefix = '', $depth = 0)
```

The data's fields, flattened: path =&gt; a sample value (author.name =&gt; 'Octavia E. Butler'), lists kept whole

**Parameters**

+ `$data` `array`
+ `$prefix`, default `''`
+ `$depth`, default `0`

Source: [framework/core/Snap/Designer.php:138](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Designer.php#L138)

<a name="snap-designer-format"></a>
#### `Designer::format()`

```php
public static function format($value, $format)
```

_No doc comment._

**Parameters**

+ `$value`
+ `$format`

Source: [framework/core/Snap/Designer.php:321](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Designer.php#L321)

<a name="snap-conversation"></a>
## class Caligrafy\Snap\Conversation

The Snap shell's two spaces (2.23.0)

Its 15 public methods have a page of their own: [Caligrafy\Snap\Conversation](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Conversation).

<a name="snap-planner"></a>
## class Caligrafy\Snap\Planner

```php
namespace Caligrafy\Snap;

class Planner
```

Source: [framework/core/Snap/Planner.php:25](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Planner.php#L25)

The Snap shell's planner (2.23.0): Claude reads what the person typed or said and answers with cards.

What the model may do, enforced here, not in the prompt:

- look things up with the read-only capabilities this person may call (as tools, run with their permissions);
- answer with show_cards: which capability, with which values, and one sentence of caption.

Every card it names goes through Snap\Flow like any other: a read runs, a change comes back as an Ask: Confirm
whose token only the person's click sends. The model never sees a token and never runs a change.
Tool results are the app's data: the system prompt says so, and nothing in them can reach a change anyway.

Claude through the official PHP SDK (anthropic-ai/sdk), claude-opus-5-5 at low effort (a quick turn in a UI),
server-side refusal fallbacks on. Without ANTHROPIC_API_KEY the planner is off and the shell uses its fast path.

### Constants

+ `MODEL = 'claude-opus-5-5'`
+ `MAX_STEPS = 6`
+ `RESULT_BYTES = 12000`
+ `FILE_TYPES = array('image/png', 'image/jpeg', 'image/gif', 'image/webp', 'application/pdf', 'text/plain', 'text/csv', 'text/markdown')`
+ `FILE_BYTES = 5242880`
+ `FILES = 3`

### Public properties

+ `public static $transport = null`: callable|null tests: fn (array $request): object  (a response with -&gt;stopReason and -&gt;content)

### Methods

+ [`Planner::on()`](#snap-planner-on)
+ [`Planner::files()`](#snap-planner-files)
+ [`Planner::plan()`](#snap-planner-plan)
+ [`Planner::send()`](#snap-planner-send)

<a name="snap-planner-on"></a>
#### `Planner::on()`

```php
public static function on()
```

_No doc comment._

Source: [framework/core/Snap/Planner.php:34](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Planner.php#L34)

<a name="snap-planner-files"></a>
#### `Planner::files()`

```php
public static function files($files)
```

The files the person attached, checked: [name, type, data (base64)] of an allowed type, 3 at most, 5 MB in all

**Parameters**

+ `$files`

+ **@throws** ServiceError invalid when a file is refused (the message says which)

Source: [framework/core/Snap/Planner.php:60](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Planner.php#L60)

<a name="snap-planner-plan"></a>
#### `Planner::plan()`

```php
public static function plan($text, Context $context, $instead = null, array $files = array(), $memory = '')
```

_No doc comment._

**Parameters**

+ `$text`
+ `$context` `Context`
+ `$instead`, default `null`
+ `$files` `array`, default `array()`
+ `$memory`, default `''`

Source: [framework/core/Snap/Planner.php:107](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Planner.php#L107)

<a name="snap-planner-send"></a>
#### `Planner::send()`

```php
public static function send(array $request)
```

_No doc comment._

**Parameters**

+ `$request` `array`

Source: [framework/core/Snap/Planner.php:163](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Planner.php#L163)

<a name="snap-flow"></a>
## class Caligrafy\Snap\Flow

```php
namespace Caligrafy\Snap;

class Flow
```

Source: [framework/core/Snap/Flow.php:16](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Flow.php#L16)

The next card for a capability and its inputs, the same whoever asks (a card that is sent, the shell's fast path,
the model's choice): one place decides, so the planner can never take a shortcut around consent.

```
read:        inputs missing -> its Ask card; complete -> runs -> Show card
write/destroy: inputs missing -> its Ask card; refused by its rules -> Ask with errors; else -> Ask: Confirm
```

A change runs only in SnapRun, with the token of that Confirm.

### Methods

+ [`Flow::next()`](#snap-flow-next)
+ [`Flow::refused()`](#snap-flow-refused)

<a name="snap-flow-next"></a>
#### `Flow::next()`

```php
public static function next($name, array $inputs, Context $context)
```

**Parameters**

+ `$name`
+ `$inputs` `array`
+ `$context` `Context`

**Returns** `array`: [card, http status]

Source: [framework/core/Snap/Flow.php:21](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Flow.php#L21)

<a name="snap-flow-refused"></a>
#### `Flow::refused()`

```php
public static function refused($name, Context $context, array $inputs, ServiceError $e)
```

_No doc comment._

**Parameters**

+ `$name`
+ `$context` `Context`
+ `$inputs` `array`
+ `$e` `ServiceError`

Source: [framework/core/Snap/Flow.php:55](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Flow.php#L55)

<a name="snap-input"></a>
## class Caligrafy\Snap\Input

```php
namespace Caligrafy\Snap;

class Input
```

Source: [framework/core/Snap/Input.php:15](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Input.php#L15)

Class Input
The inputs of a card arrive as an object, or its JSON (agents and addresses send JSON text): this gives the plain
values only (a nested object or list is left out: a card's inputs are scalars).

### Methods

+ [`Input::decode()`](#snap-input-decode)

<a name="snap-input-decode"></a>
#### `Input::decode()`

```php
public static function decode($value)
```

_No doc comment._

**Parameters**

+ `$value`

Source: [framework/core/Snap/Input.php:17](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Input.php#L17)

<a name="snap-reads"></a>
## class Caligrafy\Snap\Reads

```php
namespace Caligrafy\Snap;

class Reads
```

Source: [framework/core/Snap/Reads.php:12](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Reads.php#L12)

The reads of one request, once (2.23.0): Home asks the same lists for its alerts, insights and picks; each runs
once per person per request. Cards::forget() (after a change) forgets them too.

### Methods

+ [`Reads::plain()`](#snap-reads-plain)
+ [`Reads::forget()`](#snap-reads-forget)

<a name="snap-reads-plain"></a>
#### `Reads::plain()`

```php
public static function plain($name, Context $context)
```

A read-only capability's plain result, without inputs, once per request and person (its errors too)

**Parameters**

+ `$name`
+ `$context` `Context`

Source: [framework/core/Snap/Reads.php:19](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Reads.php#L19)

<a name="snap-reads-forget"></a>
#### `Reads::forget()`

```php
public static function forget()
```

_No doc comment._

Source: [framework/core/Snap/Reads.php:36](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Reads.php#L36)

<a name="snap-say"></a>
## class Caligrafy\Snap\Say

```php
namespace Caligrafy\Snap;

class Say
```

Source: [framework/core/Snap/Say.php:11](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Say.php#L11)

The assistant's line after every action (2.23.0): whatever the person did (sent a
form, picked a choice, confirmed, opened a row, undid, saved a shortcut), the answer carries what the assistant says
about it, shown in the conversation section. Written here, at once and for free, from what the card is; the model
writes only the captions of free questions. Also: which answers deserve a celebration.

### Methods

+ [`Say::for()`](#snap-say-for)
+ [`Say::on()`](#snap-say-on)

<a name="snap-say-for"></a>
#### `Say::for()`

```php
public static function for(array $card, $after = null)
```

The line for a card the person just reached, and whether it is a moment to celebrate

**Parameters**

+ `$card` `array`
+ `$after`, default `null`

**Returns** `array`: [say, celebrate]

Source: [framework/core/Snap/Say.php:17](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Say.php#L17)

<a name="snap-say-on"></a>
#### `Say::on()`

```php
public static function on(array $card)
```

Adds the line (and the celebration) to a card

**Parameters**

+ `$card` `array`

Source: [framework/core/Snap/Say.php:95](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Say.php#L95)

<a name="snap-consent"></a>
## class Caligrafy\Snap\Consent

```php
namespace Caligrafy\Snap;

class Consent
```

Source: [framework/core/Snap/Consent.php:20](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Consent.php#L20)

Snap consent (2.23.0): nothing that changes data runs from a card until the person confirms it.

- snap_run answers a change with an Ask: Confirm: what will change (before -&gt; after), and a one-time token bound to this person, this capability and these exact inputs, for 10 minutes, kept in the session (never in the card's address). Only the person's click on that card sends it back; a model, a page or a link cannot make one.
- A confirmed change is recorded in Caligrafy's audit log (capability snap_confirm, detail: what was confirmed).
- What the change can be undone with is decided here, from what was true before (update_), what was created (create_ -&gt; delete_), or a hint ('undo' in application/config/snap.php). Undoing is a change too: it gets its own Confirm.

### Constants

+ `TTL = 600`
+ `KEEP = 20`
+ `KEY = 'snap_consent'`

### Methods

+ [`Consent::ask()`](#snap-consent-ask)
+ [`Consent::take()`](#snap-consent-take)
+ [`Consent::undo()`](#snap-consent-undo)

<a name="snap-consent-ask"></a>
#### `Consent::ask()`

```php
public static function ask($name, Context $context, array $inputs, $message = null)
```

The Ask: Confirm card of a change, with a fresh token

**Parameters**

+ `$name`
+ `$context` `Context`
+ `$inputs` `array`
+ `$message`, default `null`

Source: [framework/core/Snap/Consent.php:29](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Consent.php#L29)

<a name="snap-consent-take"></a>
#### `Consent::take()`

```php
public static function take($token, $name, Context $context, array $inputs)
```

Whether $token confirms exactly this change by this person; a token works once

**Parameters**

+ `$token`
+ `$name`
+ `$context` `Context`
+ `$inputs` `array`

**Returns** `array|null`: what was kept with it (the values before the change)

Source: [framework/core/Snap/Consent.php:47](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Consent.php#L47)

<a name="snap-consent-undo"></a>
#### `Consent::undo()`

```php
public static function undo($name, array $inputs, $result, array $kept, Context $context)
```

The action that undoes a done change, or null when there is none

**Parameters**

+ `$name`
+ `$inputs` `array`
+ `$result`
+ `$kept` `array`
+ `$context` `Context`

Source: [framework/core/Snap/Consent.php:64](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Consent.php#L64)

<a name="snap-offers"></a>
## class Caligrafy\Snap\Offers

```php
namespace Caligrafy\Snap;

class Offers
```

Source: [framework/core/Snap/Offers.php:26](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Offers.php#L26)

Offer: Suggestion and Offer: Routine (2.23.0): the assistant notices what a person does again and again,
only if they turned noticing on, and offers to help. Built to stay quiet rather than noisy:

- opt-in per person (snap_settings.noticing), off by default; "What I've noticed" shows every pattern, each deletable, and turning noticing off deletes what was noticed
- a pattern is the same request (capability + inputs) on 3 different days or more, on the same weekday (weekly) or around the same hour (daily); anything weaker says nothing
- every offer says why ("you did this 4 Mondays in a row"), has Not now and Don't suggest this again, and at most MAX_OFFERS are shown at a time
- Offer: Suggestion: it is the usual moment and it was not done yet today: do it now (through Snap\Flow, so a change still asks for its Confirm)
- Offer: Routine: do it on that rhythm, at a level the person picks: suggest (a Suggestion at that moment), confirm (its Confirm ready at that moment), auto (it runs as a task and they are told). Accepting a routine is itself a change with its Ask: Confirm. A delete is never automatic.

### Constants

+ `MIN_DAYS = 3`
+ `MAX_OFFERS = 2`
+ `WINDOW_DAYS = 42`
+ `LEVELS = array('suggest', 'confirm', 'auto')`
+ `DAYS = array(1 => 'Monday', 2 => 'Tuesday', 3 => 'Wednesday', 4 => 'Thursday', 5 => 'Friday', 6 => 'Saturday', 7 => 'Sunday')`

### Public properties

+ `public static $now = null`: int|null tests: the time "now" is

### Methods

+ [`Offers::noticing()`](#snap-offers-noticing)
+ [`Offers::setNoticing()`](#snap-offers-setnoticing)
+ [`Offers::record()`](#snap-offers-record)
+ [`Offers::forget()`](#snap-offers-forget)
+ [`Offers::patterns()`](#snap-offers-patterns)
+ [`Offers::offers()`](#snap-offers-offers)
+ [`Offers::dismiss()`](#snap-offers-dismiss)
+ [`Offers::routines()`](#snap-offers-routines)
+ [`Offers::saveRoutine()`](#snap-offers-saveroutine)
+ [`Offers::deleteRoutine()`](#snap-offers-deleteroutine)
+ [`Offers::runDue()`](#snap-offers-rundue)
+ [`Offers::rhythmText()`](#snap-offers-rhythmtext)
+ [`Offers::fingerprint()`](#snap-offers-fingerprint)

<a name="snap-offers-noticing"></a>
#### `Offers::noticing()`

```php
public static function noticing(Context $context)
```

_No doc comment._

**Parameters**

+ `$context` `Context`

Source: [framework/core/Snap/Offers.php:39](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Offers.php#L39)

<a name="snap-offers-setnoticing"></a>
#### `Offers::setNoticing()`

```php
public static function setNoticing(Context $context, $on)
```

_No doc comment._

**Parameters**

+ `$context` `Context`
+ `$on`

Source: [framework/core/Snap/Offers.php:44](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Offers.php#L44)

<a name="snap-offers-record"></a>
#### `Offers::record()`

```php
public static function record(Context $context, $name, array $inputs)
```

Something this person did through a card (a read that ran, a change they confirmed, a task they started)

**Parameters**

+ `$context` `Context`
+ `$name`
+ `$inputs` `array`

Source: [framework/core/Snap/Offers.php:64](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Offers.php#L64)

<a name="snap-offers-forget"></a>
#### `Offers::forget()`

```php
public static function forget(Context $context, $fingerprint = null)
```

_No doc comment._

**Parameters**

+ `$context` `Context`
+ `$fingerprint`, default `null`

Source: [framework/core/Snap/Offers.php:74](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Offers.php#L74)

<a name="snap-offers-patterns"></a>
#### `Offers::patterns()`

```php
public static function patterns(Context $context)
```

What was noticed: each request done on MIN_DAYS different days or more, with its rhythm and why

**Parameters**

+ `$context` `Context`

Source: [framework/core/Snap/Offers.php:88](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Offers.php#L88)

<a name="snap-offers-offers"></a>
#### `Offers::offers()`

```php
public static function offers(Context $context)
```

The offers to show now: routines that are due, then suggestions of this moment, then routines to propose;
never more than MAX_OFFERS, never one dismissed

**Parameters**

+ `$context` `Context`

Source: [framework/core/Snap/Offers.php:121](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Offers.php#L121)

<a name="snap-offers-dismiss"></a>
#### `Offers::dismiss()`

```php
public static function dismiss(Context $context, $fingerprint, $kind)
```

_No doc comment._

**Parameters**

+ `$context` `Context`
+ `$fingerprint`
+ `$kind`

Source: [framework/core/Snap/Offers.php:147](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Offers.php#L147)

<a name="snap-offers-routines"></a>
#### `Offers::routines()`

```php
public static function routines(Context $context)
```

_No doc comment._

**Parameters**

+ `$context` `Context`

Source: [framework/core/Snap/Offers.php:162](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Offers.php#L162)

<a name="snap-offers-saveroutine"></a>
#### `Offers::saveRoutine()`

```php
public static function saveRoutine(Context $context, $capability, array $inputs, $weekday, $hour, $level)
```

Keeps a routine (snap_routine_save, after its Ask: Confirm): the consent to do it on a rhythm, recorded in the audit log

**Parameters**

+ `$context` `Context`
+ `$capability`
+ `$inputs` `array`
+ `$weekday`
+ `$hour`
+ `$level`

Source: [framework/core/Snap/Offers.php:174](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Offers.php#L174)

<a name="snap-offers-deleteroutine"></a>
#### `Offers::deleteRoutine()`

```php
public static function deleteRoutine(Context $context, $id)
```

_No doc comment._

**Parameters**

+ `$context` `Context`
+ `$id`

Source: [framework/core/Snap/Offers.php:194](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Offers.php#L194)

<a name="snap-offers-rundue"></a>
#### `Offers::runDue()`

```php
public static function runDue()
```

The scheduler's side (snap_routines_due, every minute): routines at the auto level that are due run as a task,
as their owner, and they are told (by the task). Others wait for the person, as offers.

Source: [framework/core/Snap/Offers.php:206](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Offers.php#L206)

<a name="snap-offers-rhythmtext"></a>
#### `Offers::rhythmText()`

```php
public static function rhythmText(array $r)
```

_No doc comment._

**Parameters**

+ `$r` `array`

Source: [framework/core/Snap/Offers.php:313](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Offers.php#L313)

<a name="snap-offers-fingerprint"></a>
#### `Offers::fingerprint()`

```php
public static function fingerprint($name, array $inputs)
```

_No doc comment._

**Parameters**

+ `$name`
+ `$inputs` `array`

Source: [framework/core/Snap/Offers.php:333](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Offers.php#L333)

<a name="snap-shortcuts"></a>
## class Caligrafy\Snap\Shortcuts

```php
namespace Caligrafy\Snap;

class Shortcuts
```

Source: [framework/core/Snap/Shortcuts.php:14](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Shortcuts.php#L14)

Go: Shortcut cards (2.23.0): a request a person saved (a capability with its inputs), run with one click.
Running one goes through Snap\Flow like any card: a read shows its result, a change asks for its Confirm.

### Constants

+ `TABLE = 'caligrafy_snap_shortcuts'`
+ `MAX = 12`

### Methods

+ [`Shortcuts::of()`](#snap-shortcuts-of)
+ [`Shortcuts::save()`](#snap-shortcuts-save)
+ [`Shortcuts::delete()`](#snap-shortcuts-delete)
+ [`Shortcuts::mark()`](#snap-shortcuts-mark)
+ [`Shortcuts::find()`](#snap-shortcuts-find)

<a name="snap-shortcuts-of"></a>
#### `Shortcuts::of()`

```php
public static function of(Context $context)
```

_No doc comment._

**Parameters**

+ `$context` `Context`

Source: [framework/core/Snap/Shortcuts.php:19](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Shortcuts.php#L19)

<a name="snap-shortcuts-save"></a>
#### `Shortcuts::save()`

```php
public static function save(Context $context, $title, $capability, array $inputs)
```

_No doc comment._

**Parameters**

+ `$context` `Context`
+ `$title`
+ `$capability`
+ `$inputs` `array`

Source: [framework/core/Snap/Shortcuts.php:35](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Shortcuts.php#L35)

<a name="snap-shortcuts-delete"></a>
#### `Shortcuts::delete()`

```php
public static function delete(Context $context, $id)
```

_No doc comment._

**Parameters**

+ `$context` `Context`
+ `$id`

Source: [framework/core/Snap/Shortcuts.php:49](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Shortcuts.php#L49)

<a name="snap-shortcuts-mark"></a>
#### `Shortcuts::mark()`

```php
public static function mark(array $card, Context $context)
```

A Show card says whether it is one of this person's shortcuts already (its id), so its control shows the state:
saved (with Remove) or not (Save)

**Parameters**

+ `$card` `array`
+ `$context` `Context`

Source: [framework/core/Snap/Shortcuts.php:62](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Shortcuts.php#L62)

<a name="snap-shortcuts-find"></a>
#### `Shortcuts::find()`

```php
public static function find(Context $context, $text)
```

The shortcut whose title matches what was typed, or null

**Parameters**

+ `$context` `Context`
+ `$text`

Source: [framework/core/Snap/Shortcuts.php:81](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Shortcuts.php#L81)

<a name="snap-tasks"></a>
## class Caligrafy\Snap\Tasks

```php
namespace Caligrafy\Snap;

class Tasks
```

Source: [framework/core/Snap/Tasks.php:24](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Tasks.php#L24)

Track: Task cards (2.23.0): work that runs in the background for one person.

A capability declared #[Capability(async: true)] (or with the hint 'async' in application/config/snap.php) does not run
in the request: a read starts as a task at once, a change after its Ask: Confirm. The task is a row of snap_tasks and
a job of Caligrafy's queue (snap_task_run). The worker runs the capability AS THE PERSON who asked (their user, the
web channel: their permissions, not the queue's full access), keeps the card of what came out, and notifies them:

```
done        -> the Show card of the result
needs_input -> the Ask card of what the capability refused (the person answers it, a new task starts)
failed      -> a notice, after the queue's retries
```

The Track card shows where it is: queued, running, then the card it ended with.

### Constants

+ `TABLE = 'caligrafy_snap_tasks'`
+ `LABELS = ...`

### Methods

+ [`Tasks::async()`](#snap-tasks-async)
+ [`Tasks::start()`](#snap-tasks-start)
+ [`Tasks::run()`](#snap-tasks-run)
+ [`Tasks::get()`](#snap-tasks-get)
+ [`Tasks::of()`](#snap-tasks-of)

<a name="snap-tasks-async"></a>
#### `Tasks::async()`

```php
public static function async($name)
```

_No doc comment._

**Parameters**

+ `$name`

Source: [framework/core/Snap/Tasks.php:30](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Tasks.php#L30)

<a name="snap-tasks-start"></a>
#### `Tasks::start()`

```php
public static function start($name, array $inputs, Context $context)
```

Starts a task for this person: the row, then its job. Returns its Track card.

**Parameters**

+ `$name`
+ `$inputs` `array`
+ `$context` `Context`

Source: [framework/core/Snap/Tasks.php:40](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Tasks.php#L40)

<a name="snap-tasks-run"></a>
#### `Tasks::run()`

```php
public static function run($id)
```

The worker (snap_task_run, in the queue): runs the task as its owner, keeps the card it ends with, notifies

**Parameters**

+ `$id`

Source: [framework/core/Snap/Tasks.php:55](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Tasks.php#L55)

<a name="snap-tasks-get"></a>
#### `Tasks::get()`

```php
public static function get($id, Context $context)
```

One task's Track card, for its owner only

**Parameters**

+ `$id`
+ `$context` `Context`

Source: [framework/core/Snap/Tasks.php:90](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Tasks.php#L90)

<a name="snap-tasks-of"></a>
#### `Tasks::of()`

```php
public static function of(Context $context, $limit = 6)
```

This person's latest tasks, newest first ("Coming up" and what just finished)

**Parameters**

+ `$context` `Context`
+ `$limit`, default `6`

Source: [framework/core/Snap/Tasks.php:102](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Tasks.php#L102)

<a name="snap-discover"></a>
## class Caligrafy\Snap\Discover

```php
namespace Caligrafy\Snap;

class Discover
```

Source: [framework/core/Snap/Discover.php:28](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Discover.php#L28)

Discover (2.23.0): Home surfaces the things this application is about, to
invite browsing, the way a shop surfaces products. Out of the box, from one hint on a list capability ('discover'):

- for you      more like what this person looked at (only when they turned noticing on: what they opened is in snap_events), e.g. another book by the author of a book they opened
- new          what was added last
- the rule     a business rule of the app: only what is available now (not in another list, e.g. not lent)

Each pick is a Home card that opens the object in the task space; each says why it is there.

The hint: 'discover' =&gt; array(

```
'open' => 'get_book', 'key' => 'id',                     how an object opens (capability, the field it takes)
'title' => 'title', 'meta' => array('author.name', ...),   what a pick shows
'new' => 'created_at',                                   the field that says when it was added
'related' => 'author.id', 'by' => 'author.name',          what "more like it" shares, and its name
'opened' => array('get_book' => 'id', 'lend_book' => 'book_id'),   the requests that mean "looked at it"
'unavailable' => array('capability' => 'list_loans', 'field' => 'book_id'),   the business rule
'title_section' => 'On the shelf for you')
```

### Constants

+ `PICKS = 6`

### Methods

+ [`Discover::sections()`](#snap-discover-sections)
+ [`Discover::dig()`](#snap-discover-dig)

<a name="snap-discover-sections"></a>
#### `Discover::sections()`

```php
public static function sections(Context $context)
```

**Parameters**

+ `$context` `Context`

**Returns** `array`: [title, cards, nudge] for each list capability with a 'discover' hint this person may read

Source: [framework/core/Snap/Discover.php:35](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Discover.php#L35)

<a name="snap-discover-dig"></a>
#### `Discover::dig()`

```php
public static function dig($row, $path)
```

_No doc comment._

**Parameters**

+ `$row`
+ `$path`

Source: [framework/core/Snap/Discover.php:155](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Discover.php#L155)

<a name="snap-setup"></a>
## class Caligrafy\Snap\Setup

```php
namespace Caligrafy\Snap;

class Setup
```

Source: [framework/core/Snap/Setup.php:17](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Setup.php#L17)

Class Setup
install: the tables (framework/settings/platform.sql), a starter application/config/snap.php when there is none,
then the two lines to add by hand (they are the app's own files): Route::snap(); in web.php, and the routines'
job in application/config/schedule.php.
status: each of those, the queue (tasks run in it), and the assistant's model (ANTHROPIC_API_KEY).

### Constants

+ `CONFIG = 'application/config/snap.php'`
+ `TEMPLATE = 'framework/settings/snap.php.template'`
+ `ROUTES = 'application/config/routing/web.php'`
+ `SCHEDULE = 'application/config/schedule.php'`

### Methods

+ [`Setup::status()`](#snap-setup-status)
+ [`Setup::config()`](#snap-setup-config)

<a name="snap-setup-status"></a>
#### `Setup::status()`

```php
public static function status($root = '.')
```

What is ready, and what is not: [label =&gt; [ok (bool), detail]]

**Parameters**

+ `$root`, default `'.'`

Source: [framework/core/Snap/Setup.php:27](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Setup.php#L27)

<a name="snap-setup-config"></a>
#### `Setup::config()`

```php
public static function config($root = '.')
```

Writes the starter application/config/snap.php when there is none

**Parameters**

+ `$root`, default `'.'`

**Returns** `bool`: true when it was written

Source: [framework/core/Snap/Setup.php:49](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Setup.php#L49)

<a name="snap-shell"></a>
## class Caligrafy\Snap\Shell

```php
namespace Caligrafy\Snap;

class Shell
```

Source: [framework/core/Snap/Shell.php:15](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Shell.php#L15)

The Snap shell's fast path (2.23.0): what it can answer without a model, at once and for free:

- "What can I do?" (help, menu, ?): the cards this person may use, by family
- the title of one of their shortcuts: that Go: Shortcut, run
- the title or the name of a card ("the catalog", "lend a book", "list_loans"): that card

Anything else goes to the planner (Claude) when it is on.

### Constants

+ `MENU = array('what can i do', 'what else can i do', 'what can you do', 'help', 'menu', '?', 'options')`
+ `ON_IT = ...`

### Methods

+ [`Shell::onFocus()`](#snap-shell-onfocus)
+ [`Shell::fast()`](#snap-shell-fast)
+ [`Shell::menuCard()`](#snap-shell-menucard)
+ [`Shell::menu()`](#snap-shell-menu)
+ [`Shell::normalize()`](#snap-shell-normalize)

<a name="snap-shell-onfocus"></a>
#### `Shell::onFocus()`

```php
public static function onFocus($text, Context $context, $focus)
```

A follow-up on the record the conversation is about, at once: "delete it", "change this", "lend that one".
Anything longer ("lend it to Sam") goes to the planner, with the conversation's memory.

**Parameters**

+ `$text`
+ `$context` `Context`
+ `$focus` `array|null`: ['capability' =&gt; 'get_book', 'input' =&gt; ['id' =&gt; 7]]

Source: [framework/core/Snap/Shell.php:31](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Shell.php#L31)

<a name="snap-shell-fast"></a>
#### `Shell::fast()`

```php
public static function fast($text, Context $context)
```

_No doc comment._

**Parameters**

+ `$text`
+ `$context` `Context`

Source: [framework/core/Snap/Shell.php:51](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Shell.php#L51)

<a name="snap-shell-menucard"></a>
#### `Shell::menuCard()`

```php
public static function menuCard(Context $context)
```

The menu as a card: Go: Shortcut in its menu variant (ready-made starts the system offers, not ones you saved)

**Parameters**

+ `$context` `Context`

Source: [framework/core/Snap/Shell.php:73](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Shell.php#L73)

<a name="snap-shell-menu"></a>
#### `Shell::menu()`

```php
public static function menu(Context $context)
```

The menu: every card this person may start, with its family and type

**Parameters**

+ `$context` `Context`

Source: [framework/core/Snap/Shell.php:84](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Shell.php#L84)

<a name="snap-shell-normalize"></a>
#### `Shell::normalize()`

```php
public static function normalize($text)
```

_No doc comment._

**Parameters**

+ `$text`

Source: [framework/core/Snap/Shell.php:99](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Shell.php#L99)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Cards -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Caligrafy\Snap\Cards

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Part of [Snap](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap).

<a name="snap-cards"></a>
```php
namespace Caligrafy\Snap;

class Cards
```

Source: [framework/core/Snap/Cards.php:22](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L22)

Snap Cards (2.23.0): every card is built from what a capability already declares

Families and types (marketing names the family with the type):

```
Ask: Form, Choice, Confirm   Show: Answer, List   Go: Shortcut   Track: Task   Offer: Suggestion, Routine
```

Phase 1 builds Ask: Form, Ask: Choice, Show: Answer and Show: List from:

- the capability's rules and descriptions (fields, types, limits, choices, required)
- the shape of its result (a page, a list, a record, a value)
- optional hints in application/config/snap.php (Snap\Hints)

The model, later, only picks a card and fills it; it never invents a card's structure.

## Constants

+ `VERSION = 1`
+ `MAX_OPTIONS = 50`
+ `THING_ICONS = ...`
+ `VERB_ICONS = ...`
+ `FIELD_ICONS = ...`
+ `MAX_COLUMNS = 5`
+ `LONG_TEXT = 140`
+ `HIDDEN = '/^(snap_|notify_|queue_work$)/'`

## Public properties

+ `public static $path = '/snap'`: string where Route::snap() serves the cards ('/snap' by default)

## Methods

+ [`Cards::ask()`](#snap-cards-ask)
+ [`Cards::show()`](#snap-cards-show)
+ [`Cards::confirm()`](#snap-cards-confirm)
+ [`Cards::forget()`](#snap-cards-forget)
+ [`Cards::needsInput()`](#snap-cards-needsinput)
+ [`Cards::notice()`](#snap-cards-notice)
+ [`Cards::catalog()`](#snap-cards-catalog)
+ [`Cards::fields()`](#snap-cards-fields)
+ [`Cards::url()`](#snap-cards-url)
+ [`Cards::applies()`](#snap-cards-applies)
+ [`Cards::name()`](#snap-cards-name)
+ [`Cards::risk()`](#snap-cards-risk)
+ [`Cards::icon()`](#snap-cards-icon)
+ [`Cards::title()`](#snap-cards-title)
+ [`Cards::plural()`](#snap-cards-plural)
+ [`Cards::singular()`](#snap-cards-singular)

<a name="snap-cards-ask"></a>
### `Cards::ask()`

```php
public static function ask(
    $name,
    Context $context,
    array $values = array(),
    array $errors = array(),
    $message = null,
    $asForm = false
)
```

The card that asks for a capability's inputs: Ask: Form, or Ask: Choice when one pick is all that is missing

**Parameters**

+ `$name`
+ `$context` `Context`
+ `$values` `array`, default `array()`: inputs already known (prefilled)
+ `$errors` `array`, default `array()`: field =&gt; message, from a refused call
+ `$message`, default `null`
+ `$asForm`, default `false`

Source: [framework/core/Snap/Cards.php:47](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L47)

<a name="snap-cards-show"></a>
### `Cards::show()`

```php
public static function show($name, $result, array $input, Context $context)
```

The card that shows a capability's result: Show: List for many rows, Show: Answer for one record or a value

**Parameters**

+ `$name`
+ `$result`
+ `$input` `array`
+ `$context` `Context`

Source: [framework/core/Snap/Cards.php:96](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L96)

<a name="snap-cards-confirm"></a>
### `Cards::confirm()`

```php
public static function confirm(
    $name,
    Context $context,
    array $inputs,
    $token,
    array $changes,
    $subject,
    $risk,
    $undoable,
    $message = null
)
```

Ask: Confirm: what a change will do, before it runs (phase 2). The token is the person's consent once they click;
the card's address never carries it.

**Parameters**

+ `$name`
+ `$context` `Context`
+ `$inputs` `array`
+ `$token`
+ `$changes` `array`: [label, before?, after] lines
+ `$subject`
+ `$risk`
+ `$undoable`
+ `$message`, default `null`

Source: [framework/core/Snap/Cards.php:155](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L155)

<a name="snap-cards-forget"></a>
### `Cards::forget()`

```php
public static function forget()
```

Forgets the choices read in this request (after a change, so the next card shows what is true now)

Source: [framework/core/Snap/Cards.php:192](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L192)

<a name="snap-cards-needsinput"></a>
### `Cards::needsInput()`

```php
public static function needsInput(array $ask, array $inputs)
```

Whether an Ask card still needs the person: a required input is missing, or only the id of a thing to change
was given (an update_ starts as its form). A delete needs nothing more than its id.

**Parameters**

+ `$ask` `array`
+ `$inputs` `array`

Source: [framework/core/Snap/Cards.php:202](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L202)

<a name="snap-cards-notice"></a>
### `Cards::notice()`

```php
public static function notice($name, $message, $kind = 'info', array $inputs = array())
```

A message instead of a result: a refusal that is not about the inputs (not found, conflict, forbidden)

**Parameters**

+ `$name`
+ `$message`
+ `$kind`, default `'info'`
+ `$inputs` `array`, default `array()`

Source: [framework/core/Snap/Cards.php:220](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L220)

<a name="snap-cards-catalog"></a>
### `Cards::catalog()`

```php
public static function catalog(Context $context, $run = true)
```

Every capability this person may use, as the card it starts with (the gallery of phase 1)

**Parameters**

+ `$context` `Context`
+ `$run`, default `true`

Source: [framework/core/Snap/Cards.php:234](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L234)

<a name="snap-cards-fields"></a>
### `Cards::fields()`

```php
public static function fields($name, Context $context, array $values = array(), ?array $hints = null)
```

The fields of an Ask card, from the rules: widget, limits, options, label, help, current value

**Parameters**

+ `$name`
+ `$context` `Context`
+ `$values` `array`, default `array()`
+ `$hints` `?array`, default `null`

Source: [framework/core/Snap/Cards.php:259](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L259)

<a name="snap-cards-url"></a>
### `Cards::url()`

```php
public static function url($name, array $input = array())
```

_No doc comment._

**Parameters**

+ `$name`
+ `$input` `array`, default `array()`

Source: [framework/core/Snap/Cards.php:335](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L335)

<a name="snap-cards-applies"></a>
### `Cards::applies()`

```php
public static function applies($name, array $record, Context $context)
```

Whether an action applies to a record now, from its hint 'applies':

```
'in' => array('capability' => 'list_loans', 'field' => 'book_id')       the record is in that list
'not_in' => array(...)                                                 the record is not in that list
```

The list is read as the person (once per request); one they may not read leaves the action out.

**Parameters**

+ `$name`
+ `$record` `array`
+ `$context` `Context`

Source: [framework/core/Snap/Cards.php:572](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L572)

<a name="snap-cards-name"></a>
### `Cards::name()`

```php
public static function name(array $record)
```

What a record is called: its own title or name, else the title or name of the record it is about (a loan is
about its book), else its username, else #id

**Parameters**

+ `$record` `array`

Source: [framework/core/Snap/Cards.php:600](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L600)

<a name="snap-cards-risk"></a>
### `Cards::risk()`

```php
public static function risk($capability)
```

_No doc comment._

**Parameters**

+ `$capability`

Source: [framework/core/Snap/Cards.php:620](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L620)

<a name="snap-cards-icon"></a>
### `Cards::icon()`

```php
public static function icon($name)
```

_No doc comment._

**Parameters**

+ `$name`

Source: [framework/core/Snap/Cards.php:633](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L633)

<a name="snap-cards-title"></a>
### `Cards::title()`

```php
public static function title($name)
```

_No doc comment._

**Parameters**

+ `$name`

Source: [framework/core/Snap/Cards.php:646](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L646)

<a name="snap-cards-plural"></a>
### `Cards::plural()`

```php
public static function plural($word)
```

_No doc comment._

**Parameters**

+ `$word`

Source: [framework/core/Snap/Cards.php:699](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L699)

<a name="snap-cards-singular"></a>
### `Cards::singular()`

```php
public static function singular($word)
```

_No doc comment._

**Parameters**

+ `$word`

Source: [framework/core/Snap/Cards.php:704](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Cards.php#L704)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap-Conversation -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Caligrafy\Snap\Conversation

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Part of [Snap](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap).

<a name="snap-conversation"></a>
```php
namespace Caligrafy\Snap;

class Conversation
```

Source: [framework/core/Snap/Conversation.php:19](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L19)

The Snap shell's two spaces (2.23.0):

```
Home       the starting workspace: the agent's message for the situation, prompt suggestions (and "What else can
           I do"), the input; then the cards: Needs you (alerts, tasks waiting on you, changes to confirm),
           For you (offers), In progress (tasks), Shortcuts. Only the sections that have something.
Task space the engagement: the conversation minimized to the agent's latest answer (back and forth, history,
           rating, a different answer, the input on demand); only the cards of that answer.
```

Each turn is kept (snap_turns): what was asked, the caption, the cards, the suggestions, how it was answered.

## Constants

+ `TABLE = 'caligrafy_snap_turns'`
+ `MORE = 'What else can I do?'`
+ `HOME = 'Back to Home'`

## Methods

+ [`Conversation::installed()`](#snap-conversation-installed)
+ [`Conversation::save()`](#snap-conversation-save)
+ [`Conversation::turns()`](#snap-conversation-turns)
+ [`Conversation::last()`](#snap-conversation-last)
+ [`Conversation::history()`](#snap-conversation-history)
+ [`Conversation::rate()`](#snap-conversation-rate)
+ [`Conversation::memory()`](#snap-conversation-memory)
+ [`Conversation::suggestions()`](#snap-conversation-suggestions)
+ [`Conversation::empty()`](#snap-conversation-empty)
+ [`Conversation::lower()`](#snap-conversation-lower)
+ [`Conversation::home()`](#snap-conversation-home)
+ [`Conversation::open()`](#snap-conversation-open)
+ [`Conversation::needs()`](#snap-conversation-needs)
+ [`Conversation::insights()`](#snap-conversation-insights)
+ [`Conversation::progress()`](#snap-conversation-progress)

<a name="snap-conversation-installed"></a>
### `Conversation::installed()`

```php
public static function installed()
```

Whether Snap's tables are there (php caligrafer.php platform install): checked once per request

Source: [framework/core/Snap/Conversation.php:28](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L28)

<a name="snap-conversation-save"></a>
### `Conversation::save()`

```php
public static function save(Context $context, $conversation, $text, array $answer)
```

_No doc comment._

**Parameters**

+ `$context` `Context`
+ `$conversation`
+ `$text`
+ `$answer` `array`

Source: [framework/core/Snap/Conversation.php:44](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L44)

<a name="snap-conversation-turns"></a>
### `Conversation::turns()`

```php
public static function turns(Context $context, $conversation)
```

_No doc comment._

**Parameters**

+ `$context` `Context`
+ `$conversation`

Source: [framework/core/Snap/Conversation.php:52](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L52)

<a name="snap-conversation-last"></a>
### `Conversation::last()`

```php
public static function last(Context $context, $turnId)
```

_No doc comment._

**Parameters**

+ `$context` `Context`
+ `$turnId`

Source: [framework/core/Snap/Conversation.php:74](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L74)

<a name="snap-conversation-history"></a>
### `Conversation::history()`

```php
public static function history(Context $context, $limit = 20)
```

This person's conversations, newest first: their first question is their title

**Parameters**

+ `$context` `Context`
+ `$limit`, default `20`

Source: [framework/core/Snap/Conversation.php:86](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L86)

<a name="snap-conversation-rate"></a>
### `Conversation::rate()`

```php
public static function rate(Context $context, $turnId, $rating)
```

_No doc comment._

**Parameters**

+ `$context` `Context`
+ `$turnId`
+ `$rating`

Source: [framework/core/Snap/Conversation.php:103](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L103)

<a name="snap-conversation-memory"></a>
### `Conversation::memory()`

```php
public static function memory(Context $context, $conversation, $sent)
```

The conversation's memory for the next ask: its earlier turns (what was asked, what was shown), what is on the
person's screen now, what they chose since (opened, picked, confirmed), and what it is about (the focus: "it").
What the page sends is checked and cut to size; it is the person's own context, and the planner is told it is
data from the app, never instructions.

**Parameters**

+ `$context` `Context`
+ `$conversation`
+ `$sent`

**Returns** `array`: ['focus' =&gt; array|null, 'text' =&gt; string] (text empty: nothing to remember)

Source: [framework/core/Snap/Conversation.php:121](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L121)

<a name="snap-conversation-suggestions"></a>
### `Conversation::suggestions()`

```php
public static function suggestions(array $cards, Context $context)
```

What the person may want to do next, beyond the buttons of the cards on screen: the optional details a form
still takes, what follows a change (another one, the list it belongs to), what a list leads to, then
"What else can I do?". Each suggestion carries what it runs, so a click is at once a card, without a model.

**Parameters**

+ `$cards` `array`
+ `$context` `Context`

Source: [framework/core/Snap/Conversation.php:174](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L174)

<a name="snap-conversation-empty"></a>
### `Conversation::empty()`

```php
public static function empty(array $card)
```

_No doc comment._

**Parameters**

+ `$card` `array`

Source: [framework/core/Snap/Conversation.php:232](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L232)

<a name="snap-conversation-lower"></a>
### `Conversation::lower()`

```php
public static function lower($text)
```

_No doc comment._

**Parameters**

+ `$text`

Source: [framework/core/Snap/Conversation.php:324](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L324)

<a name="snap-conversation-home"></a>
### `Conversation::home()`

```php
public static function home(Context $context)
```

Home, for this person, now: an orchestrator of what to concentrate on, in this order:

```
Needs you      alerts, tasks waiting on the person, changes to confirm (the focus)
insights       numbers, each with the action it calls for (none without one)
For you        offers (what they usually do now, routines)
In progress    running tasks
discover       the things this app is about, to browse: more like what they looked at, new, available
Just done, Your shortcuts
```

The message says the focus and nudges the conversation on; the suggestions start with the focus's action and a
pick to look at. One card per capability (the latest task of a capability is its only card) and per object.
Each card carries its key: opening it (snap_ask open) shows it in the task space.

**Parameters**

+ `$context` `Context`

Source: [framework/core/Snap/Conversation.php:343](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L343)

<a name="snap-conversation-open"></a>
### `Conversation::open()`

```php
public static function open(Context $context, $key)
```

A Home card opened in the task space, by its key: a shortcut runs what it saved; anything else is shown in full,
with the assistant's line

**Parameters**

+ `$context` `Context`
+ `$key`

**Returns** `array`: the answer: caption, cards, via, text

Source: [framework/core/Snap/Conversation.php:436](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L436)

<a name="snap-conversation-needs"></a>
### `Conversation::needs()`

```php
public static function needs(Context $context, ?array $tasks = null)
```

Needs you: alerts (a hint 'alert' on a read capability whose rows carry a flag), tasks that wait on the person
(needs your answer, could not finish), routines waiting for their confirm. Each one carries its next step.

**Parameters**

+ `$context` `Context`
+ `$tasks` `?array`, default `null`

Source: [framework/core/Snap/Conversation.php:481](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L481)

<a name="snap-conversation-insights"></a>
### `Conversation::insights()`

```php
public static function insights(Context $context)
```

Insights: numbers that call for something. One per read capability with an 'insight' hint, shown only when there
is something to act on (a count above zero) and this person may take its action; each carries that action.

```
'insight' => array('label', 'icon', 'action' => array('capability', 'text'),
                   'since' => array('field', 'days')?   count only what was added lately
                   'ring' => array('of', 'label', 'invert')?)   and a share of another count
```

**Parameters**

+ `$context` `Context`

Source: [framework/core/Snap/Conversation.php:535](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L535)

<a name="snap-conversation-progress"></a>
### `Conversation::progress()`

```php
public static function progress(Context $context)
```

The person's progress: what they got done today through the app, and how many days in a row they did something
(from Caligrafy's audit log: their successful changes; the assistant's own bookkeeping is left out)

**Parameters**

+ `$context` `Context`

Source: [framework/core/Snap/Conversation.php:582](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Snap/Conversation.php#L582)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Testing -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Testing

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

The base class of the tests of an application (tests/, php caligrafer.php test).

| Class | What it is |
|---|---|
| [`Caligrafy\Testing\TestCase`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Testing#testing-testcase) | Test what the app does through its capabilities, as the pages, REST, the JS client and agents reach them |

<a name="testing-testcase"></a>
## abstract class Caligrafy\Testing\TestCase

```php
namespace Caligrafy\Testing;

abstract class TestCase extends \PHPUnit\Framework\TestCase
```

Source: [framework/testing/TestCase.php:41](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/testing/TestCase.php#L41)

Test what the app does through its capabilities, as the pages, REST, the JS client and agents reach them:

```
final class BooksTest extends Caligrafy\Testing\TestCase
{
    public function testAReaderAddsABook(): void
    {
        $book = $this->call('create_book', ['title' => 'Dune'], $this->user(1));
        $this->assertSame('Dune', $book['title']);
        $this->assertCapabilityFails('invalid', 'create_book', [], $this->user(1));
        $this->assertCapabilityFails('unauthenticated', 'create_book', ['title' => 'Dune'], 'guest');
        $this->assertStringContainsString('Dune', $this->render('Books/list', ['books' => [$book]]));
    }
}
```

Each test runs in a database transaction that is rolled back at its end (with DB_ACTIVATE=true), so tests leave the
database as they found it; a CREATE, ALTER or DROP ends the transaction (MySQL commits it). Use a database of its own
for tests: DB_TEST_DATABASE in .env, or the settings of .env.testing. Bindings of the container, the cache's copies
and the query shapes the N+1 warning counts (Query::forgetShapes) are forgotten between tests.

### Methods

+ [`->setUp()`](#testing-testcase-setup)
+ [`->tearDown()`](#testing-testcase-teardown)
+ [`->call()`](#testing-testcase-call)
+ [`->action()`](#testing-testcase-action)
+ [`->assertCapabilityFails()`](#testing-testcase-assertcapabilityfails)
+ [`->user()`](#testing-testcase-user)
+ [`->render()`](#testing-testcase-render)
+ [`->fake()`](#testing-testcase-fake)
+ [`->assertQueued()`](#testing-testcase-assertqueued)

<a name="testing-testcase-setup"></a>
#### `->setUp()`

```php
protected function setUp(): void
```

_No doc comment._

**Returns** `void`

Source: [framework/testing/TestCase.php:48](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/testing/TestCase.php#L48)

<a name="testing-testcase-teardown"></a>
#### `->tearDown()`

```php
protected function tearDown(): void
```

_No doc comment._

**Returns** `void`

Source: [framework/testing/TestCase.php:65](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/testing/TestCase.php#L65)

<a name="testing-testcase-call"></a>
#### `->call()`

```php
protected function call($capability, array $input = array(), $as = null)
```

Calls a capability as a channel would, with its permission checks, validation and audit

**Parameters**

+ `$capability`
+ `$input` `array`, default `array()`
+ `$as` `Context|object|array|string|null`, default `null`: null: the command line (full access); 'guest'; a user (see user()); or a Context

**Returns** `mixed`: its answer

Source: [framework/testing/TestCase.php:84](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/testing/TestCase.php#L84)

<a name="testing-testcase-action"></a>
#### `->action()`

```php
protected function action($capability, array $input = array(), $as = null)
```

Calls a webOnly capability as Route::action() does (2.21.0)

**Parameters**

+ `$capability`
+ `$input` `array`, default `array()`
+ `$as`, default `null`

**Returns** `mixed`: its answer: a Caligrafy\Web (describe() says what it answers), or plain data

Source: [framework/testing/TestCase.php:93](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/testing/TestCase.php#L93)

<a name="testing-testcase-assertcapabilityfails"></a>
#### `->assertCapabilityFails()`

```php
protected function assertCapabilityFails($kind, $capability, array $input = array(), $as = null)
```

Asserts that a capability refuses: invalid, unauthenticated, forbidden, not_found or conflict

**Parameters**

+ `$kind`
+ `$capability`
+ `$input` `array`, default `array()`
+ `$as`, default `null`

**Returns** `ServiceError`: the error, to check its message or fields

Source: [framework/testing/TestCase.php:104](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/testing/TestCase.php#L104)

<a name="testing-testcase-user"></a>
#### `->user()`

```php
protected function user($id = 1, $level = 0, array $attributes = array())
```

A signed-in user for call(): an id and a permission level (the users column Context::$levelAttribute), plus any
other attributes the capability reads

**Parameters**

+ `$id`, default `1`
+ `$level`, default `0`
+ `$attributes` `array`, default `array()`

Source: [framework/testing/TestCase.php:119](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/testing/TestCase.php#L119)

<a name="testing-testcase-render"></a>
#### `->render()`

```php
protected function render($view, array $data = array())
```

The HTML of a Pug view of application/views, as a page would show it

**Parameters**

+ `$view`
+ `$data` `array`, default `array()`

Source: [framework/testing/TestCase.php:127](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/testing/TestCase.php#L127)

<a name="testing-testcase-fake"></a>
#### `->fake()`

```php
protected function fake($id, $object)
```

Replaces what the container gives for $id (a mailer, a payment gateway) with $object, for this test

**Parameters**

+ `$id`
+ `$object`

Source: [framework/testing/TestCase.php:141](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/testing/TestCase.php#L141)

<a name="testing-testcase-assertqueued"></a>
#### `->assertQueued()`

```php
protected function assertQueued($capability, ?callable $where = null)
```

Asserts that a job of this capability was pushed to the queue (in this test), and returns its input

**Parameters**

+ `$capability`
+ `$where` `?callable`, default `null`

Source: [framework/testing/TestCase.php:150](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/testing/TestCase.php#L150)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Framework and tooling

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

The framework bootstrap and what the caligrafer command runs: the CLI, doctor, update, upgrade, deploy, Cloud, quickstart and the plugin copy.

| Class | What it is |
|---|---|
| [`Caligrafy\Features`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#features) | The SDKs that only some applications use are no longer in Caligrafy's composer.json (they are suggested): a project adds the one it needs with php caligrafer.php add &lt;feature&gt;, which runs composer require with the ... |
| [`Caligrafy\FeatureMissing`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#featuremissing) | A feature whose SDK (or files) this project does not install: the message names the command that adds it |
| [`Caligrafy\Framework`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#framework) | Class Framework that loads the entire framework Framework loader |
| [`Caligrafy\Loader`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#loader) | Class Loader loads any additional librairies and helpers needed per module Framework loader loads any additional librairies and helpers needed per module |
| [`Caligrafy\ClassMap`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#classmap) | Before 2.18.0 the first unknown class of a request loaded every PHP file of framework/core, framework/database, framework/interfaces, application/ and tests/. |
| [`Caligrafy\Caligrafer`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#caligrafer) | Class Caligrafer: the framework as the command line starts it (php caligrafer.php): settings, constants and the class map, without routes or a session cookie |
| [`Caligrafy\Doctor`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#doctor) | Every check is read-only: it lists, reads or connects, it never creates, charges or sends anything (the only exception is Watson when its assistants cannot be listed: a session is opened and closed right away). |
| [`Caligrafy\Updater`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#updater) | php caligrafer.php update [&lt;version&gt;] downloads the project's release (Framework::VERSION) and the target release (the latest by default), then: 1. framework/ and claude-plugin/ are the framework's: replaced whole ... |
| [`Caligrafy\Upgrader`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#upgrader) | Compares application/ with framework/settings/application and reports or applies the template updates. |
| [`Caligrafy\Deployer`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#deployer) | 1. waits for the database (a new server starts its database at the same time as the app) 2. creates the framework tables (framework/settings/platform.sql, safe to run again) 3. runs every ... |
| [`Caligrafy\CloudClient`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#cloudclient) | Calls the capabilities of Caligrafy Cloud (POST &lt;url&gt;/capabilities/&lt;name&gt;) with a personal access token of the account. |
| [`Caligrafy\Quickstart`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#quickstart) | Every step can be run again: it only does what is missing. |
| [`Caligrafy\PluginSource`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#pluginsource) | A project enables the Claude Code plugin of its own claude-plugin/ folder through .claude/settings.json: a plugin source (a "marketplace", declared in .claude-plugin/marketplace.json) at "./", and the plugin ... |

<a name="features"></a>
## class Caligrafy\Features

```php
namespace Caligrafy;

class Features
```

Source: [framework/core/Features.php:30](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L30)

Class Features (2.26.0)
The SDKs that only some applications use are no longer in Caligrafy's composer.json (they are suggested): a project
adds the one it needs with php caligrafer.php add &lt;feature&gt;, which runs composer require with the pinned constraint.
The framework classes that use an SDK call Features::need() first: without it they throw FeatureMissing, whose
message names the command, never a fatal "class not found".

FaceDetect's models (@vladmandic/face-api 1.7.15) and the pictures of its recognition example are not in the release
either: php caligrafer.php add facedetect (and php caligrafer.php facedetect &lt;app&gt;) download them from pinned,
versioned sources and check the SHA-256 of each file before anything is written.

used() tells which features a project uses (its .env settings and its application/ code): doctor reports the ones
whose SDK is missing, update keeps (or adds back) their packages in composer.json.

### Constants

+ `SINCE = '2.26.0'`
+ `FEATURES = ...`
+ `CLASSES = ...`
+ `PLACEHOLDERS = array('pk_test_1234', 'sk_test_1234', 'pk_live_1234', 'sk_live_1234')`
+ `FACE_API = '1.7.15'`
+ `MODELS_DIR = 'public/resources/models'`
+ `MODELS = ...`
+ `MODEL_SOURCES = array('https://cdn.jsdelivr.net/npm/@vladmandic/face-api@1.7.15/model/', 'https://unpkg.com/@vladmandic/face-api@1.7.15/model/',)`
+ `PICTURES_DIR = 'recognition/Flash'`
+ `PICTURES = ...`
+ `PICTURE_SOURCES = ...`

### Public properties

+ `public static $absent = array()`: array tests: packages treated as not installed
+ `public static $fetcher = null`: callable|null tests: fn (string $url): ?string, the body of a download (null when it failed)

### Methods

+ [`Features::names()`](#features-names)
+ [`Features::installedPackage()`](#features-installedpackage)
+ [`Features::missing()`](#features-missing)
+ [`Features::installed()`](#features-installed)
+ [`Features::need()`](#features-need)
+ [`Features::message()`](#features-message)
+ [`Features::requireCommand()`](#features-requirecommand)
+ [`Features::used()`](#features-used)
+ [`Features::toRestore()`](#features-torestore)
+ [`Features::add()`](#features-add)
+ [`Features::facedetectReady()`](#features-facedetectready)
+ [`Features::modelFiles()`](#features-modelfiles)
+ [`Features::pictureFiles()`](#features-picturefiles)
+ [`Features::download()`](#features-download)

<a name="features-names"></a>
#### `Features::names()`

```php
public static function names()
```

The feature names: payments, ai, push, passkeys, snap (SDKs) and facedetect (files)

Source: [framework/core/Features.php:141](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L141)

<a name="features-installedpackage"></a>
#### `Features::installedPackage()`

```php
public static function installedPackage($package)
```

Whether a package is installed (its class loads)

**Parameters**

+ `$package`

Source: [framework/core/Features.php:149](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L149)

<a name="features-missing"></a>
#### `Features::missing()`

```php
public static function missing($feature)
```

The packages of a feature that are not installed: [name =&gt; constraint]

**Parameters**

+ `$feature`

Source: [framework/core/Features.php:159](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L159)

<a name="features-installed"></a>
#### `Features::installed()`

```php
public static function installed($feature)
```

_No doc comment._

**Parameters**

+ `$feature`

Source: [framework/core/Features.php:165](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L165)

<a name="features-need"></a>
#### `Features::need()`

```php
public static function need($feature, $what)
```

Throws FeatureMissing when the feature's SDK is not installed

**Parameters**

+ `$feature`
+ `$what` `string`: what needs it (Caligrafy\Payment, new Agent() with Groq...)

Source: [framework/core/Features.php:174](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L174)

<a name="features-message"></a>
#### `Features::message()`

```php
public static function message($feature, $what = null)
```

The message of a missing SDK: what needs it, the packages, the command that installs them

**Parameters**

+ `$feature`
+ `$what`, default `null`

Source: [framework/core/Features.php:183](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L183)

<a name="features-requirecommand"></a>
#### `Features::requireCommand()`

```php
public static function requireCommand(array $features)
```

The composer require command of features: composer require --no-interaction 'a/b:^1' ...

**Parameters**

+ `$features` `array`

Source: [framework/core/Features.php:193](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L193)

<a name="features-used"></a>
#### `Features::used()`

```php
public static function used($root = '.', $env = null)
```

The features a project uses: [feature =&gt; [reasons]], from its .env settings (set, not a placeholder) and its
application/ code. Values of .env are never returned, only the names of the settings

**Parameters**

+ `$root`, default `'.'`
+ `$env` `callable|null`, default `null`: fn(string $name): string, a setting (default: the project's .env file)

Source: [framework/core/Features.php:209](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L209)

<a name="features-torestore"></a>
#### `Features::toRestore()`

```php
public static function toRestore($root, array $composer, $env = null)
```

The require entries a project's composer.json lacks for the features it uses: [package =&gt; [constraint, feature,
reason]]. Packages it already requires (any constraint) are left alone

**Parameters**

+ `$root`
+ `$composer` `array`
+ `$env`, default `null`

Source: [framework/core/Features.php:242](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L242)

<a name="features-add"></a>
#### `Features::add()`

```php
public static function add(array $features, $root = '.', $run = null, $out = null)
```

php caligrafer.php add &lt;feature&gt;...: composer require for the SDKs, the downloads for facedetect

**Parameters**

+ `$features` `array`
+ `$root`, default `'.'`
+ `$run` `callable|null`, default `null`: fn(string $command): int (tests fake Composer)
+ `$out` `callable|null`, default `null`: fn(string $line)

**Returns** `int`: exit code

Source: [framework/core/Features.php:260](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L260)

<a name="features-facedetectready"></a>
#### `Features::facedetectReady()`

```php
public static function facedetectReady($root = '.')
```

Whether the FaceDetect models are in place (each file there with its size)

**Parameters**

+ `$root`, default `'.'`

Source: [framework/core/Features.php:307](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L307)

<a name="features-modelfiles"></a>
#### `Features::modelFiles()`

```php
public static function modelFiles($root = '.')
```

The model files: [path, sha256, size, urls]

**Parameters**

+ `$root`, default `'.'`

Source: [framework/core/Features.php:318](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L318)

<a name="features-picturefiles"></a>
#### `Features::pictureFiles()`

```php
public static function pictureFiles($appDir)
```

The pictures of the recognition example of a FaceDetect app (its folder)

**Parameters**

+ `$appDir`

Source: [framework/core/Features.php:326](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L326)

<a name="features-download"></a>
#### `Features::download()`

```php
public static function download(array $files)
```

Downloads the files that are missing, checks the SHA-256 of each, then writes them all; nothing is written when
one fails. A file already there with another content is left alone (yours)

**Parameters**

+ `$files` `array`

**Returns** `array`: lines of the report

+ **@throws** \RuntimeException offline, or a download that does not match its SHA-256

Source: [framework/core/Features.php:337](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L337)

<a name="featuremissing"></a>
## class Caligrafy\FeatureMissing

```php
namespace Caligrafy;

class FeatureMissing extends \LogicException
```

Source: [framework/core/Features.php:14](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Features.php#L14)

A feature whose SDK (or files) this project does not install: the message names the command that adds it

_No public methods._

<a name="framework"></a>
## class Caligrafy\Framework

```php
namespace Caligrafy;

class Framework extends \stdClass
```

Source: [framework/core/Framework.php:19](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Framework.php#L19)

Class Framework that loads the entire framework
Framework loader

### Constants

+ `VERSION = '2.26.0'`: Version of Caligrafy Quill (semantic versioning: the git tag is v&lt;VERSION&gt;, the changes are in CHANGELOG.md)

### Methods

+ [`Framework::run()`](#framework-run)
+ [`Framework::mappedFolders()`](#framework-mappedfolders)
+ [`Framework::unmappedFolders()`](#framework-unmappedfolders)

<a name="framework-run"></a>
#### `Framework::run()`

```php
public static function run()
```

Framework main

Source: [framework/core/Framework.php:29](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Framework.php#L29)

<a name="framework-mappedfolders"></a>
#### `Framework::mappedFolders()`

```php
public static function mappedFolders()
```

The folders of the class map: the framework's classes and the application's

Source: [framework/core/Framework.php:78](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Framework.php#L78)

<a name="framework-unmappedfolders"></a>
#### `Framework::unmappedFolders()`

```php
public static function unmappedFolders()
```

Left out of the class map: settings and routes (loaded by dispatch), views (Pug)

Source: [framework/core/Framework.php:86](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Framework.php#L86)

<a name="loader"></a>
## class Caligrafy\Loader

```php
namespace Caligrafy;

class Loader extends \stdClass
```

Source: [framework/core/Loader.php:20](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Loader.php#L20)

Class Loader loads any additional librairies and helpers needed per module
Framework loader loads any additional librairies and helpers needed per module

### Methods

+ [`->library()`](#loader-library)
+ [`->helper()`](#loader-helper)

<a name="loader-library"></a>
#### `->library()`

```php
public function library($lib)
```

_No doc comment._

**Parameters**

+ `$lib`

Source: [framework/core/Loader.php:23](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Loader.php#L23)

<a name="loader-helper"></a>
#### `->helper()`

```php
public function helper($helper)
```

_No doc comment._

**Parameters**

+ `$helper`

Source: [framework/core/Loader.php:28](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Loader.php#L28)

<a name="classmap"></a>
## class Caligrafy\ClassMap

```php
namespace Caligrafy;

class ClassMap
```

Source: [framework/core/ClassMap.php:24](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ClassMap.php#L24)

Class ClassMap (2.18.0)
Before 2.18.0 the first unknown class of a request loaded every PHP file of framework/core, framework/database,
framework/interfaces, application/ and tests/. Now a map of class =&gt; file (namespaced or not, interfaces, traits and
enums too) is built once from those folders (application/config, application/views and tests/ left out) and kept in a
private folder of the temporary directory; a class is loaded when it is first used.

Kept as before: a file that does more than declare classes (it declares functions, or runs code at the top level, or
declares a class inside an if) is loaded at start, as every file used to be. A class missing from the map, and the
list of capabilities, make the map check its files (once per request; with APP_ENV=production at most once a
minute): a file added, removed or changed since the map was built rebuilds it, so a new class works at once while
you develop. A new container starts with no map. CLASS_MAP=false in .env goes back to loading every file.

### Constants

+ `VERSION = 2`
+ `PRODUCTION_CHECK = 60`

### Methods

+ [`ClassMap::enabled()`](#classmap-enabled)
+ [`ClassMap::register()`](#classmap-register)
+ [`ClassMap::load()`](#classmap-load)
+ [`ClassMap::capabilityFiles()`](#classmap-capabilityfiles)
+ [`ClassMap::refresh()`](#classmap-refresh)
+ [`ClassMap::registered()`](#classmap-registered)
+ [`ClassMap::map()`](#classmap-map)
+ [`ClassMap::rebuild()`](#classmap-rebuild)
+ [`ClassMap::declarations()`](#classmap-declarations)
+ [`ClassMap::tempFolder()`](#classmap-tempfolder)

<a name="classmap-enabled"></a>
#### `ClassMap::enabled()`

```php
public static function enabled()
```

Whether the class map is on (CLASS_MAP=false turns it off)

Source: [framework/core/ClassMap.php:38](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ClassMap.php#L38)

<a name="classmap-register"></a>
#### `ClassMap::register()`

```php
public static function register(array $dirs, array $skip = array())
```

Registers the autoloader for these folders and loads the files that must run at start

**Parameters**

+ `$dirs` `array`: absolute folders to map
+ `$skip` `array`, default `array()`: absolute folders inside them to leave out

Source: [framework/core/ClassMap.php:48](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ClassMap.php#L48)

<a name="classmap-load"></a>
#### `ClassMap::load()`

```php
public static function load($class)
```

The autoloader

**Parameters**

+ `$class`

Source: [framework/core/ClassMap.php:78](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ClassMap.php#L78)

<a name="classmap-capabilityfiles"></a>
#### `ClassMap::capabilityFiles()`

```php
public static function capabilityFiles($fresh = false)
```

The files that may declare capabilities (they mention #[Capability]): Capabilities loads them to find every one

**Parameters**

+ `$fresh`, default `false`

Source: [framework/core/ClassMap.php:93](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ClassMap.php#L93)

<a name="classmap-refresh"></a>
#### `ClassMap::refresh()`

```php
public static function refresh()
```

Rebuilds the map when a file was added, removed or edited since it was built (checked once per request)

Source: [framework/core/ClassMap.php:107](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ClassMap.php#L107)

<a name="classmap-registered"></a>
#### `ClassMap::registered()`

```php
public static function registered()
```

Whether the autoloader is registered

Source: [framework/core/ClassMap.php:133](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ClassMap.php#L133)

<a name="classmap-map"></a>
#### `ClassMap::map()`

```php
public static function map()
```

The map, from memory, the cached file or a new scan

Source: [framework/core/ClassMap.php:141](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ClassMap.php#L141)

<a name="classmap-rebuild"></a>
#### `ClassMap::rebuild()`

```php
public static function rebuild()
```

Scans the folders again and saves the map

Source: [framework/core/ClassMap.php:158](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ClassMap.php#L158)

<a name="classmap-declarations"></a>
#### `ClassMap::declarations()`

```php
public static function declarations($source)
```

What a PHP file declares at its top level: its classes (with their namespace), and whether it does anything else
(functions, code, a class declared inside a block), which makes it a file to load at start

**Parameters**

+ `$source`

**Returns** `array`: ['classes' =&gt; [...], 'eager' =&gt; bool]

Source: [framework/core/ClassMap.php:250](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ClassMap.php#L250)

<a name="classmap-tempfolder"></a>
#### `ClassMap::tempFolder()`

```php
public static function tempFolder($kind)
```

A private folder of the system's temporary directory for this project, this system user and one kind of cache
(views, classes, data): created 0700, null when it cannot be created or written, is a link, or someone else owns it

**Parameters**

+ `$kind`

Source: [framework/core/ClassMap.php:339](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/ClassMap.php#L339)

<a name="caligrafer"></a>
## class Caligrafy\Caligrafer

```php
namespace Caligrafy;

class Caligrafer extends \stdClass
```

Source: [framework/core/Caligrafer.php:20](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Caligrafer.php#L20)

Class Caligrafer: the framework as the command line starts it (php caligrafer.php): settings, constants and the
class map, without routes or a session cookie

### Methods

+ [`Caligrafer::run()`](#caligrafer-run)
+ [`Caligrafer::generateKeys()`](#caligrafer-generatekeys)
+ [`Caligrafer::generateApiKey()`](#caligrafer-generateapikey)
+ [`Caligrafer::dispatch()`](#caligrafer-dispatch)

<a name="caligrafer-run"></a>
#### `Caligrafer::run()`

```php
public static function run()
```

Caligrafer main

Source: [framework/core/Caligrafer.php:25](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Caligrafer.php#L25)

<a name="caligrafer-generatekeys"></a>
#### `Caligrafer::generateKeys()`

```php
public static function generateKeys()
```

Generates Keys from the command line

Source: [framework/core/Caligrafer.php:35](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Caligrafer.php#L35)

<a name="caligrafer-generateapikey"></a>
#### `Caligrafer::generateApiKey()`

```php
public static function generateApiKey()
```

Generates Api Key from the command line

Source: [framework/core/Caligrafer.php:49](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Caligrafer.php#L49)

<a name="caligrafer-dispatch"></a>
#### `Caligrafer::dispatch()`

```php
public static function dispatch()
```

Dispatches the URL to the route

Source: [framework/core/Caligrafer.php:100](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Caligrafer.php#L100)

<a name="doctor"></a>
## class Caligrafy\Doctor

```php
namespace Caligrafy;

class Doctor
```

Source: [framework/core/Doctor.php:22](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Doctor.php#L22)

Class Doctor
Every check is read-only: it lists, reads or connects, it never creates, charges or sends anything
(the only exception is Watson when its assistants cannot be listed: a session is opened and closed right away).
Secret values are never printed: at most a known prefix and the last 4 characters.

Base URLs can be overridden (tests, proxies, regional endpoints): OPENAI_API_BASE, GROQ_API_BASE, AGENT_API_BASE,
STRIPE_API_BASE, COINBASE_API_BASE. Watson always uses WATSON_URL.

### Constants

+ `CHECKS =['project', 'database', 'openai', 'groq', 'agent', 'stripe', 'coinbase', 'watson', 'mail']`
+ `LABELS = ...`
+ `TIMEOUT = 8`
+ `PLACEHOLDERS =['your-smtp-host', 'pk_test_1234', 'sk_test_1234', 'pk_live_1234', 'sk_live_1234']`
+ `PREFIXES =['sk-proj-', 'sk-svcacct-', 'sk-admin-', 'gsk_', 'sk_test_', 'sk_live_', 'rk_test_', 'rk_live_', 'pk_test_', 'pk_live_']`

### Methods

+ [`->__construct()`](#doctor-construct)
+ [`->run()`](#doctor-run)
+ [`->results()`](#doctor-results)
+ [`Doctor::formsWithoutMethod()`](#doctor-formswithoutmethod)
+ [`Doctor::pugPitfalls()`](#doctor-pugpitfalls)
+ [`Doctor::mask()`](#doctor-mask)

<a name="doctor-construct"></a>
#### `->__construct()`

```php
public function __construct($root = '.', $only = null, $envFile = '.env')
```

_No doc comment._

**Parameters**

+ `$root`, default `'.'`
+ `$only`, default `null`
+ `$envFile`, default `'.env'`

Source: [framework/core/Doctor.php:40](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Doctor.php#L40)

<a name="doctor-run"></a>
#### `->run()`

```php
public function run($json = false)
```

Runs the checks and prints the report

**Parameters**

+ `$json`, default `false`

**Returns** `int`: exit code: 0 without FAIL, 1 otherwise

Source: [framework/core/Doctor.php:51](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Doctor.php#L51)

<a name="doctor-results"></a>
#### `->results()`

```php
public function results()
```

_No doc comment._

Source: [framework/core/Doctor.php:85](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Doctor.php#L85)

<a name="doctor-formswithoutmethod"></a>
#### `Doctor::formsWithoutMethod()`

```php
public static function formsWithoutMethod($root)
```

The forms of application/views (Pug) with an email or a password field and no method: "file:line" each

**Parameters**

+ `$root`

Source: [framework/core/Doctor.php:791](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Doctor.php#L791)

<a name="doctor-pugpitfalls"></a>
#### `Doctor::pugPitfalls()`

```php
public static function pugPitfalls($root)
```

Pug mistakes of application/views that only show when the page renders: "file:line $digits" for a dollar sign
before digits (outside comments), "file:line - if" for code on the same line as a one-line - if / - foreach

**Parameters**

+ `$root`

Source: [framework/core/Doctor.php:822](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Doctor.php#L822)

<a name="doctor-mask"></a>
#### `Doctor::mask()`

```php
public static function mask($value)
```

_No doc comment._

**Parameters**

+ `$value`

Source: [framework/core/Doctor.php:849](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Doctor.php#L849)

<a name="updater"></a>
## class Caligrafy\Updater

```php
namespace Caligrafy;

class Updater
```

Source: [framework/core/Updater.php:26](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Updater.php#L26)

Class Updater
php caligrafer.php update [&lt;version&gt;] downloads the project's release (Framework::VERSION) and the target release
(the latest by default), then:
1. framework/ and claude-plugin/ are the framework's: replaced whole (files the release dropped go too), except the files initialize writes there (KEEP). Framework files changed by hand are named in the report
2. every other file of the release (caligrafer.php, .bin/, Dockerfile, index.php, public/css, public/js...) is compared with the project's release: an untouched copy is replaced, a missing one added, a changed one kept with the new version written next to it (&lt;file&gt;.caligrafy-new). Documents (DOCS) changed by hand are left alone
3. composer.json gets the new packages and versions the project did not change (then composer update for them), .gitignore the new lines, .env the new settings with their defaults (existing values are never changed)
4. php caligrafer.php upgrade --apply, from the new release, brings application/ up to date
Everything replaced is copied first to backups/caligrafy-update-&lt;from&gt;-to-&lt;to&gt;-&lt;time&gt;/. --check reports only.
application/, .env values, public/uploads and vendor/ are never replaced.

### Constants

+ `REPOSITORY = 'caligrafy/caligrafy-quill'`
+ `WHOLE = array('framework', 'claude-plugin')`
+ `KEEP = array('framework/librairies/app/.env')`
+ `SKIP = ...`
+ `MERGED = array('composer.json', '.gitignore')`
+ `DOCS = array('README.md', 'CHANGELOG.md', 'CONTRIBUTING.md', 'CODE_OF_CONDUCT.md', 'ARCHITECTURE.md', 'LICENSE')`
+ `NEW_SUFFIX = '.caligrafy-new'`
+ `ENV_EXAMPLE = 'framework/settings/.env.example'`

### Methods

+ [`->__construct()`](#updater-construct)
+ [`->run()`](#updater-run)
+ [`->newerRelease()`](#updater-newerrelease)
+ [`->download()`](#updater-download)

<a name="updater-construct"></a>
#### `->__construct()`

```php
public function __construct($root = '.', $fetch = null, $run = null)
```

**Parameters**

+ `$root` `string`, default `'.'`: the project
+ `$fetch` `callable|null`, default `null`: fn(string $version): string folder of that release, null when it does not exist; fn('latest') gives the latest version number (tests)
+ `$run` `callable|null`, default `null`: fn(string $command): int, runs a shell command in the project (tests)

Source: [framework/core/Updater.php:59](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Updater.php#L59)

<a name="updater-run"></a>
#### `->run()`

```php
public function run($target = null, $check = false, $yes = false, $composer = true)
```

**Parameters**

+ `$target` `string|null`, default `null`: a version (2.8.0, v2.8.0) or null for the latest
+ `$check` `bool`, default `false`: report only
+ `$yes` `bool`, default `false`: go on although git has uncommitted changes
+ `$composer` `bool`, default `true`: run composer update for changed packages

**Returns** `int`: exit code

Source: [framework/core/Updater.php:74](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Updater.php#L74)

<a name="updater-newerrelease"></a>
#### `->newerRelease()`

```php
public function newerRelease()
```

The latest release when it is newer than the project's, for upgrade: [version or null, why it could not tell or null]

Source: [framework/core/Updater.php:350](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Updater.php#L350)

<a name="updater-download"></a>
#### `->download()`

```php
public function download($version)
```

The release folder of a version, downloaded from GitHub and unpacked in a temporary folder; 'latest' gives the
latest version number

**Parameters**

+ `$version`

Source: [framework/core/Updater.php:368](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Updater.php#L368)

<a name="upgrader"></a>
## class Caligrafy\Upgrader

```php
namespace Caligrafy;

class Upgrader
```

Source: [framework/core/Upgrader.php:18](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Upgrader.php#L18)

Class Upgrader
Compares application/ with framework/settings/application and reports or applies the template updates.
Only template files are touched; files you created, .env, public/uploads and vendor are never read or written.
Client apps in public/ created from framework/plugins are reported only, and so are .env (new and obsolete settings)
and the views or apps that still use Bootstrap 3 classes (the framework uses Bootstrap 5).

### Constants

+ `TEMPLATE = 'framework/settings/application'`
+ `HISTORY = 'framework/settings/template-history.json'`
+ `USER_SERVICES = 'services/Users/'`
+ `ADMIN_CONTROLLER = 'controllers/core/Auth/AdminController.php'`
+ `AUTH_CONTROLLER = 'controllers/core/Auth/AuthController.php'`
+ `PLUGINS = 'framework/plugins'`
+ `MANIFEST = '.caligrafy-manifest.json'`
+ `ROUTES = 'config/routing/web.php'`
+ `NEW_SUFFIX = '.caligrafy-new'`
+ `MANIFEST_FORMAT = 1`
+ `PLUGIN_MARKERS =['facedetect' => 'new FaceDetector', 'ml' => 'new MlCore', 'bot' => '__bots__', 'app' => 'loadVue(']`
+ `BOOTSTRAP3 = ...`
+ `OBSOLETE_SETTINGS =['CRYPTO_PAY_KEY' => 'Coinbase Commerce closed on March 31, 2026: use COINBASE_API_KEY_NAME and COINBASE_API_KEY_SECRET (Coinbase Business)']`

### Public properties

+ `public static $composer = null`: callable|null tests: fn(string $command): int, runs composer instead of the shell

### Methods

+ [`->__construct()`](#upgrader-construct)
+ [`Upgrader::hashes()`](#upgrader-hashes)
+ [`Upgrader::writeManifest()`](#upgrader-writemanifest)
+ [`->plan()`](#upgrader-plan)
+ [`->run()`](#upgrader-run)

<a name="upgrader-construct"></a>
#### `->__construct()`

```php
public function __construct($root = '.', $apply = false, $force = null, $keep = array())
```

**Parameters**

+ `$root`, default `'.'`
+ `$apply`, default `false`
+ `$force`, default `null`
+ `$keep` `array`, default `array()`: application/ paths to keep even though they are untouched copies of an older template (a default page that became a page of the site, like the home page): the new version is written next to them, as for customized files

Source: [framework/core/Upgrader.php:51](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Upgrader.php#L51)

<a name="upgrader-hashes"></a>
#### `Upgrader::hashes()`

```php
public static function hashes($dir)
```

sha256 of every file of a folder, keyed by relative path (.DS_Store and node_modules skipped)

**Parameters**

+ `$dir`

Source: [framework/core/Upgrader.php:64](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Upgrader.php#L64)

<a name="upgrader-writemanifest"></a>
#### `Upgrader::writeManifest()`

```php
public static function writeManifest($root = '.', $files = null, $kept = array())
```

Writes application/.caligrafy-manifest.json (called by initialize after copying the templates)

**Parameters**

+ `$root`, default `'.'`
+ `$files`, default `null`
+ `$kept`, default `array()`

Source: [framework/core/Upgrader.php:81](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Upgrader.php#L81)

<a name="upgrader-plan"></a>
#### `->plan()`

```php
public function plan()
```

Compares every template file with application/

**Returns** `array`: path =&gt; ['status' =&gt; missing|identical|outdated|customized|routes, 'template' =&gt; hash, 'current' =&gt; hash|null]

Source: [framework/core/Upgrader.php:101](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Upgrader.php#L101)

<a name="upgrader-run"></a>
#### `->run()`

```php
public function run()
```

Prints the plan and, with --apply or --force, applies it

Source: [framework/core/Upgrader.php:199](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Upgrader.php#L199)

<a name="deployer"></a>
## class Caligrafy\Deployer

```php
namespace Caligrafy;

class Deployer
```

Source: [framework/core/Deployer.php:23](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Deployer.php#L23)

Class Deployer
1. waits for the database (a new server starts its database at the same time as the app)
2. creates the framework tables (framework/settings/platform.sql, safe to run again)
3. runs every application/models/&lt;folder&gt;/create_db.sql that is new or changed since its last run, and records it in caligrafy_scripts. A script that drops, deletes or truncates is never run again once it ran: run it by hand (php caligrafer.php sql &lt;file&gt;) when you mean it. seed.sql and other scripts are never run. A statement that adds a column, an index or a foreign key already there (the script's earlier run added it) is skipped, so a script keeps its ALTER TABLE ... ADD statements.
4. runs the migrations of application/migrations that never ran (Migrations, 2.18.0)
Without DB_ACTIVATE=true there is nothing to do.

### Constants

+ `SCRIPTS_TABLE = 'caligrafy_scripts'`
+ `DESTRUCTIVE = '/\b(DROP\s+(TABLE|DATABASE|SCHEMA|VIEW|COLUMN)|DELETE\s+FROM|TRUNCATE)\b/i'`

### Methods

+ [`->__construct()`](#deployer-construct)
+ [`->run()`](#deployer-run)
+ [`Deployer::cacheEnv()`](#deployer-cacheenv)
+ [`->schedule()`](#deployer-schedule)
+ [`->scripts()`](#deployer-scripts)
+ [`Deployer::destructive()`](#deployer-destructive)
+ [`Deployer::alreadyApplied()`](#deployer-alreadyapplied)

<a name="deployer-construct"></a>
#### `->__construct()`

```php
public function __construct($root = '.', $wait = 60)
```

**Parameters**

+ `$root` `string`, default `'.'`: the project folder
+ `$wait` `int`, default `60`: seconds to wait for the database

Source: [framework/core/Deployer.php:36](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Deployer.php#L36)

<a name="deployer-run"></a>
#### `->run()`

```php
public function run()
```

**Returns** `int`: exit code: 0 when the project is ready, 1 when the database could not be prepared

Source: [framework/core/Deployer.php:45](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Deployer.php#L45)

<a name="deployer-cacheenv"></a>
#### `Deployer::cacheEnv()`

```php
public static function cacheEnv($root = '.')
```

Compiles .env to .env.php (2.19.0): the values Dotenv reads from it, as a PHP array that index.php includes
(OPcache keeps it) instead of parsing .env on every request. Same owner, group and permissions as .env; written
to a temporary file, then renamed. index.php uses it only while .env still has the content it was compiled from (its sha1).

**Parameters**

+ `$root`, default `'.'`

**Returns** `bool`: false without a .env

Source: [framework/core/Deployer.php:81](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Deployer.php#L81)

<a name="deployer-schedule"></a>
#### `->schedule()`

```php
public function schedule()
```

Prints the scheduled jobs (application/config/schedule.php) on one line of the start-up log, where Caligrafy
Cloud reads them: "caligrafy-schedule &lt;the listing of schedule list --json&gt;", or "caligrafy-schedule-invalid
&lt;the problems&gt;" (the jobs then do not run). Without the file the listing is empty.

Source: [framework/core/Deployer.php:115](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Deployer.php#L115)

<a name="deployer-scripts"></a>
#### `->scripts()`

```php
public function scripts()
```

application/models/&lt;folder&gt;/create_db.sql files, in folder order

Source: [framework/core/Deployer.php:130](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Deployer.php#L130)

<a name="deployer-destructive"></a>
#### `Deployer::destructive()`

```php
public static function destructive($sql)
```

Whether a script drops, deletes or truncates data

**Parameters**

+ `$sql`

Source: [framework/core/Deployer.php:140](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Deployer.php#L140)

<a name="deployer-alreadyapplied"></a>
#### `Deployer::alreadyApplied()`

```php
public static function alreadyApplied(\Throwable $e)
```

Whether a statement failed only because what it adds is already there (MySQL and MariaDB: duplicate column 1060,
duplicate key name 1061, duplicate foreign key 1826), so a changed create_db.sql can keep its ALTER TABLE ... ADD
statements and run again

**Parameters**

+ `$e` `\Throwable`

Source: [framework/core/Deployer.php:211](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Deployer.php#L211)

<a name="cloudclient"></a>
## class Caligrafy\CloudClient

```php
namespace Caligrafy;

class CloudClient
```

Source: [framework/core/CloudClient.php:19](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/CloudClient.php#L19)

Class CloudClient
Calls the capabilities of Caligrafy Cloud (POST &lt;url&gt;/capabilities/&lt;name&gt;) with a personal access token of the
account. `cloud login` gets it by itself: it opens &lt;url&gt;/cli?code=..., the owner approves the code shown in the
terminal, and the command collects the token (start_cli_login, poll_cli_login). --token or --paste take one created
on the dashboard instead. The token is kept in .caligrafy/cloud.json of the project (git-ignored, never in the
image), or given with CALIGRAFY_CLOUD_TOKEN. CALIGRAFY_CLOUD_URL points to another service.

### Constants

+ `DEFAULT_URL = 'https://deploy.caligrafy.com'`
+ `PERIODS = array('week', 'month', 'year')`

### Methods

+ [`->__construct()`](#cloudclient-construct)
+ [`->run()`](#cloudclient-run)
+ [`->call()`](#cloudclient-call)

<a name="cloudclient-construct"></a>
#### `->__construct()`

```php
public function __construct($root = '.', $http = null, $sleep = null)
```

**Parameters**

+ `$root`, default `'.'`
+ `$http` `callable|null`, default `null`: fn(string $method, string $url, array $headers, ?string $body): [int $status, string $body] (tests)
+ `$sleep` `callable|null`, default `null`: fn(int $seconds) between two checks of a sign-in or a deployment (tests)

Source: [framework/core/CloudClient.php:32](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/CloudClient.php#L32)

<a name="cloudclient-run"></a>
#### `->run()`

```php
public function run(array $args)
```

**Parameters**

+ `$args` `array`: the words after "cloud"

**Returns** `int`: exit code

Source: [framework/core/CloudClient.php:43](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/CloudClient.php#L43)

<a name="cloudclient-call"></a>
#### `->call()`

```php
public function call($capability, array $input = array(), $signedIn = true)
```

Calls a capability: returns its data, or throws a RuntimeException with its message (and field messages)

**Parameters**

+ `$capability`
+ `$input` `array`, default `array()`
+ `$signedIn`, default `true`

Source: [framework/core/CloudClient.php:161](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/CloudClient.php#L161)

<a name="quickstart"></a>
## class Caligrafy\Quickstart

```php
namespace Caligrafy;

class Quickstart
```

Source: [framework/core/Quickstart.php:23](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Quickstart.php#L23)

Class Quickstart
Every step can be run again: it only does what is missing.
1. application/ (initialize; it deletes the .git folder of the framework, so it needs --yes when one exists)
2. .env: the database of the Docker server (DB_ACTIVATE=true, DB_HOST=mysql, a database name), or, on a local server (MAMP, XAMPP, LAMP), the address of the project in its web folder (APP_ROOT) and its MySQL settings (asked with the stack's defaults; without a terminal to confirm them, skipped unless --db-defaults)
3. the database and the framework tables (tokens, audit log)
4. web.php: Route::capabilities('/capabilities') for the JS client, Route::mcp('/mcp') for AI agents and Route::notifications() for the links of notification emails
5. with --example: the Tasks example (capabilities, page, REST routes, table, JS client)

### Constants

+ `EXAMPLE = 'framework/settings/examples/tasks'`
+ `LOCAL_STACKS = ...`
+ `DEFAULT_DATABASE = 'caligrafy'`
+ `DOCKER_SERVICES = array('dev-box' => array(80, '8080'), 'prod-box' => array(80, '8080'), 'phpmyadmin' => array(80, '8077'), 'mysql' => array(3306, '3306'))`: Runs the steps
+ `COMPOSE_FILES = ...`

### Methods

+ [`->__construct()`](#quickstart-construct)
+ [`Quickstart::dockerPort()`](#quickstart-dockerport)
+ [`Quickstart::publishedPort()`](#quickstart-publishedport)
+ [`Quickstart::composePort()`](#quickstart-composeport)
+ [`->run()`](#quickstart-run)
+ [`Quickstart::stacks()`](#quickstart-stacks)
+ [`Quickstart::localSite()`](#quickstart-localsite)
+ [`Quickstart::addRoutes()`](#quickstart-addroutes)
+ [`Quickstart::envSet()`](#quickstart-envset)
+ [`Quickstart::envValue()`](#quickstart-envvalue)

<a name="quickstart-construct"></a>
#### `->__construct()`

```php
public function __construct($root = '.', ?callable $out = null)
```

_No doc comment._

**Parameters**

+ `$root`, default `'.'`
+ `$out` `?callable`, default `null`

Source: [framework/core/Quickstart.php:53](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Quickstart.php#L53)

<a name="quickstart-dockerport"></a>
#### `Quickstart::dockerPort()`

```php
public static function dockerPort($root = '.', $service = 'dev-box')
```

The port of this computer that reaches a service of the Docker server (dev-box by default; 2.21.8, 2.24.0):
first what Docker published (running containers: every compose file, overrides and variables counted), else the
compose files with their override (docker-compose.override.yml, which the projects of a computer use to move
8080, 8077 and 3306 when another project holds them), else the usual port

**Parameters**

+ `$root`, default `'.'`
+ `$service` `string`, default `'dev-box'`: dev-box, prod-box, phpmyadmin or mysql

Source: [framework/core/Quickstart.php:77](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Quickstart.php#L77)

<a name="quickstart-publishedport"></a>
#### `Quickstart::publishedPort()`

```php
public static function publishedPort($root, $service, $inside)
```

The port Docker published for a service of this project (docker compose port), or null: Docker missing or off,
the service not running, or inside a container (no docker command there)

**Parameters**

+ `$root`
+ `$service`
+ `$inside`

Source: [framework/core/Quickstart.php:98](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Quickstart.php#L98)

<a name="quickstart-composeport"></a>
#### `Quickstart::composePort()`

```php
public static function composePort($compose, $service, $inside)
```

The port of this computer a compose file maps to a service's port inside its container ("8170:80",
"127.0.0.1:8170:80", "${WEB_PORT:-8080}:80"), or null when the file does not say

**Parameters**

+ `$compose`
+ `$service`
+ `$inside`

Source: [framework/core/Quickstart.php:112](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Quickstart.php#L112)

<a name="quickstart-run"></a>
#### `->run()`

```php
public function run(array $options = array())
```

_No doc comment._

**Parameters**

+ `$options` `array`, default `array()`

Source: [framework/core/Quickstart.php:141](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Quickstart.php#L141)

<a name="quickstart-stacks"></a>
#### `Quickstart::stacks()`

```php
public static function stacks($mamp = '/Applications/MAMP')
```

LOCAL_STACKS with what MAMP is really set to on this computer, when it is installed: its web folder (Apache's
DocumentRoot), its address (Listen) and its MySQL port (--port). Many installs serve another folder than htdocs
and use 80 and 3306 instead of 8888 and 8889

**Parameters**

+ `$mamp`, default `'/Applications/MAMP'`

Source: [framework/core/Quickstart.php:322](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Quickstart.php#L322)

<a name="quickstart-localsite"></a>
#### `Quickstart::localSite()`

```php
public static function localSite($dir, array $stacks)
```

Where a folder is served by a known local server: ['name', 'url', 'appRoot', 'db'], or null outside their web folders

**Parameters**

+ `$dir` `string`: the real path of the project
+ `$stacks` `array`: LOCAL_STACKS

Source: [framework/core/Quickstart.php:348](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Quickstart.php#L348)

<a name="quickstart-addroutes"></a>
#### `Quickstart::addRoutes()`

```php
public static function addRoutes($source, array $lines, $comment)
```

Inserts lines before Route::run() in a web.php, under a comment, unless every line is already there

**Parameters**

+ `$source` `string`: the content of web.php
+ `$lines` `array`: the route lines (without indentation)
+ `$comment` `string`: one line that says what they are

**Returns** `string`: the new content (the same when nothing was missing)

Source: [framework/core/Quickstart.php:425](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Quickstart.php#L425)

<a name="quickstart-envset"></a>
#### `Quickstart::envSet()`

```php
public static function envSet($env, array $values)
```

Sets KEY=value lines in the content of a .env (replaces the line, or adds it at the end)

**Parameters**

+ `$env`
+ `$values` `array`

Source: [framework/core/Quickstart.php:455](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Quickstart.php#L455)

<a name="quickstart-envvalue"></a>
#### `Quickstart::envValue()`

```php
public static function envValue($env, $key)
```

The value of a KEY in the content of a .env (without an inline # comment), '' when it is not set

**Parameters**

+ `$env`
+ `$key`

Source: [framework/core/Quickstart.php:471](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/Quickstart.php#L471)

<a name="pluginsource"></a>
## class Caligrafy\PluginSource

```php
namespace Caligrafy;

class PluginSource
```

Source: [framework/core/PluginSource.php:22](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/PluginSource.php#L22)

Class PluginSource
A project enables the Claude Code plugin of its own claude-plugin/ folder through .claude/settings.json: a plugin
source (a "marketplace", declared in .claude-plugin/marketplace.json) at "./", and the plugin caligrafy-quill@&lt;name&gt;.
Claude Code keeps one source per name for the whole computer: when every project calls it "caligrafy", the first
project opened wins, every other project gets that project's plugin (an older one), and none gets any once that
folder is deleted. initialize and update give the project its own name: caligrafy-&lt;folder&gt;-&lt;4 hex&gt;.
The framework's own repository keeps "caligrafy": it is the source people add from GitHub.
Claude Code runs a copy of the plugin it makes at install time (~/.claude/plugins/cache), not the project's folder:
after an update brings a newer claude-plugin/, connect() refreshes that copy, and doctor warns while it is older.

### Constants

+ `SHARED = 'caligrafy'`
+ `PLUGIN = 'caligrafy-quill'`
+ `SETTINGS = '.claude/settings.json'`
+ `MARKETPLACE = '.claude-plugin/marketplace.json'`
+ `MANIFEST = 'claude-plugin/.claude-plugin/plugin.json'`

### Methods

+ [`PluginSource::name()`](#pluginsource-name)
+ [`PluginSource::ensureOwn()`](#pluginsource-ensureown)
+ [`PluginSource::registeredPath()`](#pluginsource-registeredpath)
+ [`PluginSource::projectVersion()`](#pluginsource-projectversion)
+ [`PluginSource::installedVersion()`](#pluginsource-installedversion)
+ [`PluginSource::connect()`](#pluginsource-connect)
+ [`PluginSource::isFramework()`](#pluginsource-isframework)

<a name="pluginsource-name"></a>
#### `PluginSource::name()`

```php
public static function name($root = '.')
```

The name of the project's plugin source, or null when the project has no plugin source files

**Parameters**

+ `$root`, default `'.'`

Source: [framework/core/PluginSource.php:33](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/PluginSource.php#L33)

<a name="pluginsource-ensureown"></a>
#### `PluginSource::ensureOwn()`

```php
public static function ensureOwn($root = '.')
```

Renames a shared "caligrafy" source to the project's own name, in both files

**Parameters**

+ `$root`, default `'.'`

**Returns** `string|null`: the new name, or null when there was nothing to rename

Source: [framework/core/PluginSource.php:43](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/PluginSource.php#L43)

<a name="pluginsource-registeredpath"></a>
#### `PluginSource::registeredPath()`

```php
public static function registeredPath($name, $home = null)
```

Where Claude Code on this computer reads the source of that name (~/.claude/plugins/known_marketplaces.json),
or null when it does not know it yet

**Parameters**

+ `$name`
+ `$home`, default `null`

Source: [framework/core/PluginSource.php:75](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/PluginSource.php#L75)

<a name="pluginsource-projectversion"></a>
#### `PluginSource::projectVersion()`

```php
public static function projectVersion($root = '.')
```

The version of the plugin in the project's claude-plugin/ folder, or null

**Parameters**

+ `$root`, default `'.'`

Source: [framework/core/PluginSource.php:89](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/PluginSource.php#L89)

<a name="pluginsource-installedversion"></a>
#### `PluginSource::installedVersion()`

```php
public static function installedVersion($name, $root = '.', $home = null)
```

The version of the copy Claude Code runs for this project (~/.claude/plugins/installed_plugins.json: installed
for the project, else for the user), or null when the plugin is not installed

**Parameters**

+ `$name`
+ `$root`, default `'.'`
+ `$home`, default `null`

Source: [framework/core/PluginSource.php:99](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/PluginSource.php#L99)

<a name="pluginsource-connect"></a>
#### `PluginSource::connect()`

```php
public static function connect($root, $say, $run = null)
```

Registers the project's plugin source with Claude Code on this computer and installs the plugin for the project
(claude plugin marketplace add &lt;folder&gt;, claude plugin install caligrafy-quill@&lt;name&gt; --scope project). An
already trusted folder is never asked again, so starting claude there does not register a renamed source

**Parameters**

+ `$root`
+ `$say` `callable`: fn(string $line)
+ `$run` `callable|null`, default `null`: fn(string $command): [int $code, string $output] (tests)

**Returns** `int`: exit code

Source: [framework/core/PluginSource.php:127](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/PluginSource.php#L127)

<a name="pluginsource-isframework"></a>
#### `PluginSource::isFramework()`

```php
public static function isFramework($root = '.')
```

_No doc comment._

**Parameters**

+ `$root`, default `'.'`

Source: [framework/core/PluginSource.php:183](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/core/PluginSource.php#L183)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Helpers -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Helper functions

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

The global functions of `framework/helpers`, loaded for every request and command.

## corehelpers.php

+ [`generateKey()`](#fn-generatekey)
+ [`generateToken()`](#fn-generatetoken)
+ [`encryptDecrypt()`](#fn-encryptdecrypt)
+ [`isSessionExpired()`](#fn-issessionexpired)
+ [`saveInSession()`](#fn-saveinsession)
+ [`clearFromSession()`](#fn-clearfromsession)
+ [`scripts()`](#fn-scripts)
+ [`design_stylesheet()`](#fn-design-stylesheet)
+ [`copyright()`](#fn-copyright)
+ [`keywords()`](#fn-keywords)
+ [`metadata()`](#fn-metadata)
+ [`session()`](#fn-session)
+ [`caligrafySessionNeeded()`](#fn-caligrafysessionneeded)
+ [`caligrafySessionReady()`](#fn-caligrafysessionready)
+ [`caligrafySessionMustSave()`](#fn-caligrafysessionmustsave)
+ [`caligrafySessionStart()`](#fn-caligrafysessionstart)
+ [`caligrafySessionSnapshot()`](#fn-caligrafysessionsnapshot)
+ [`caligrafySessionShutdown()`](#fn-caligrafysessionshutdown)
+ [`view()`](#fn-view)
+ [`api()`](#fn-api)
+ [`findKey()`](#fn-findkey)
+ [`recursive_filter()`](#fn-recursive-filter)
+ [`loadConstantFromArray()`](#fn-loadconstantfromarray)
+ [`terminateSession()`](#fn-terminatesession)
+ [`getGlobalInformation()`](#fn-getglobalinformation)
+ [`isAllowedUpload()`](#fn-isallowedupload)
+ [`uploadFile()`](#fn-uploadfile)
+ [`deleteFile()`](#fn-deletefile)
+ [`isJson()`](#fn-isjson)
+ [`sanitize()`](#fn-sanitize)
+ [`request()`](#fn-request)
+ [`connect()`](#fn-connect)
+ [`import()`](#fn-import)
+ [`parsePath()`](#fn-parsepath)
+ [`currentRoute()`](#fn-currentroute)
+ [`currentBind()`](#fn-currentbind)
+ [`startWith()`](#fn-startwith)
+ [`endWith()`](#fn-endwith)
+ [`sanitizePath()`](#fn-sanitizepath)
+ [`associate()`](#fn-associate)
+ [`bindRouteToVar()`](#fn-bindroutetovar)
+ [`parseRoute()`](#fn-parseroute)
+ [`_require_all()`](#fn-require-all)
+ [`singularize()`](#fn-singularize)
+ [`methodField()`](#fn-methodfield)
+ [`csrf()`](#fn-csrf)
+ [`errors()`](#fn-errors)
+ [`old()`](#fn-old)
+ [`flash()`](#fn-flash)
+ [`authorize()`](#fn-authorize)
+ [`authorized()`](#fn-authorized)
+ [`unauthorize()`](#fn-unauthorize)
+ [`user()`](#fn-user)
+ [`guard()`](#fn-guard)
+ [`logout()`](#fn-logout)
+ [`imageCanva()`](#fn-imagecanva)
+ [`load_script()`](#fn-load-script)
+ [`redirect()`](#fn-redirect)
+ [`getRelativeTime()`](#fn-getrelativetime)
+ [`rearrange()`](#fn-rearrange)
+ [`httpFile()`](#fn-httpfile)
+ [`httpRequest()`](#fn-httprequest)
+ [`now()`](#fn-now)
+ [`sendMail()`](#fn-sendmail)
+ [`arraySort()`](#fn-arraysort)

<a name="fn-generatekey"></a>
### `generateKey()`

```php
function generateKey($size = 32)
```

_No doc comment._

**Parameters**

+ `$size`, default `32`

Source: [framework/helpers/corehelpers.php:26](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L26)

<a name="fn-generatetoken"></a>
### `generateToken()`

```php
function generateToken($size = 12)
```

_No doc comment._

**Parameters**

+ `$size`, default `12`

Source: [framework/helpers/corehelpers.php:31](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L31)

<a name="fn-encryptdecrypt"></a>
### `encryptDecrypt()`

```php
function encryptDecrypt($action, $data, $key = APP_KEY)
```

Encryption and Decryption methods used for key identification of entities

**Parameters**

+ `$action` `string`: to specify whether it is an ecryption or decryption
+ `$data`
+ `$key`, default `APP_KEY`

**Returns** `string`: of the encrypted or decrypted field

Source: [framework/helpers/corehelpers.php:43](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L43)

<a name="fn-issessionexpired"></a>
### `isSessionExpired()`

```php
function isSessionExpired($time = SESSION_EXPIRATION_TIME)
```

Checks if a session expired and if it is the session is terminated

**Parameters**

+ `$time` `int`, default `SESSION_EXPIRATION_TIME`: passes a time argument to override the default session_expiration_time if needed

Source: [framework/helpers/corehelpers.php:77](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L77)

<a name="fn-saveinsession"></a>
### `saveInSession()`

```php
function saveInSession($input_data, $session_variable)
```

Saves forms in a session array

**Parameters**

+ `$input_data` `array`: of all variables saved in form
+ `$session_variable` `string`: identifies the session array where data should be saved

Source: [framework/helpers/corehelpers.php:94](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L94)

<a name="fn-clearfromsession"></a>
### `clearFromSession()`

```php
function clearFromSession($session_variable)
```

Clears data from a specific session variable

**Parameters**

+ `$session_variable` `string`: identifies the session array where data has been saved

Source: [framework/helpers/corehelpers.php:110](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L110)

<a name="fn-scripts"></a>
### `scripts()`

```php
function scripts($key, $value = null)
```

Gets/Sets script from session by key name

**Parameters**

+ `$key` `string`: defines the keyname to look for in the session variables
+ `$value`, default `null`

Source: [framework/helpers/corehelpers.php:127](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L127)

<a name="fn-design-stylesheet"></a>
### `design_stylesheet()`

```php
function design_stylesheet()
```

URL of the override stylesheet of the design style selected in .env (DESIGN_STYLE), loaded after the Caligrafy
stylesheets; '' for Caligrafy's own look (empty setting, unknown style or stylesheet not written yet)

Source: [framework/helpers/corehelpers.php:139](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L139)

<a name="fn-copyright"></a>
### `copyright()`

```php
function copyright($value = null)
```

Gets the copyright signature from session

**Parameters**

+ `$value`, default `null`

Source: [framework/helpers/corehelpers.php:149](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L149)

<a name="fn-keywords"></a>
### `keywords()`

```php
function keywords($value = null)
```

Gets/Sets the keywords

**Parameters**

+ `$value`, default `null`

Source: [framework/helpers/corehelpers.php:162](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L162)

<a name="fn-metadata"></a>
### `metadata()`

```php
function metadata($pairs = array())
```

Gets/Sets a metadata variable by key

**Parameters**

+ `$pairs`, default `array()`

Source: [framework/helpers/corehelpers.php:175](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L175)

<a name="fn-session"></a>
### `session()`

```php
function session($key, $value = null)
```

Gets/Sets a session variable by key

**Parameters**

+ `$key`
+ `$value`, default `null`

Source: [framework/helpers/corehelpers.php:190](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L190)

<a name="fn-caligrafysessionneeded"></a>
### `caligrafySessionNeeded()`

```php
function caligrafySessionNeeded($key, $value, $ready)
```

Whether session($key, $value) needs the session started (2.19.0): reading the CSRF token always does (it is handed
to a page or a client), a write does once the request's settings ran ($ready, caligrafySessionSnapshot()). The
settings (coresettings.php, config.php) write scripts, metadata, keywords... on every request: they stay in memory.

**Parameters**

+ `$key`
+ `$value`
+ `$ready`

Source: [framework/helpers/corehelpers.php:207](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L207)

<a name="fn-caligrafysessionready"></a>
### `caligrafySessionReady()`

```php
function caligrafySessionReady()
```

Whether the request's settings ran (caligrafySessionSnapshot() was called)

Source: [framework/helpers/corehelpers.php:218](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L218)

<a name="fn-caligrafysessionmustsave"></a>
### `caligrafySessionMustSave()`

```php
function caligrafySessionMustSave($snapshot, array $session, $output)
```

Whether a request that came without a session cookie must save its session when it ends (2.19.0): it changed
$_SESSION after the snapshot, or its output carries the CSRF token (a form posts it back)

**Parameters**

+ `$snapshot`
+ `$session` `array`
+ `$output`

Source: [framework/helpers/corehelpers.php:227](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L227)

<a name="fn-caligrafysessionstart"></a>
### `caligrafySessionStart()`

```php
function caligrafySessionStart()
```

Starts the session of a request that came without a session cookie (2.19.0): the values this request already put in
$_SESSION are kept. True when the session is active.

Source: [framework/helpers/corehelpers.php:240](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L240)

<a name="fn-caligrafysessionsnapshot"></a>
### `caligrafySessionSnapshot()`

```php
function caligrafySessionSnapshot()
```

What the session holds once the settings ran (config.php sets metadata, keywords...): a request that changes it
afterwards, or whose page carries the CSRF token, gets its session saved (caligrafySessionShutdown)

Source: [framework/helpers/corehelpers.php:261](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L261)

<a name="fn-caligrafysessionshutdown"></a>
### `caligrafySessionShutdown()`

```php
function caligrafySessionShutdown()
```

_No doc comment._

Source: [framework/helpers/corehelpers.php:271](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L271)

<a name="fn-view"></a>
### `view()`

```php
function view($viewName, $viewData = array())
```

Generic view function that instantiates a View class

**Parameters**

+ `$viewName`
+ `$viewData`, default `array()`

Source: [framework/helpers/corehelpers.php:288](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L288)

<a name="fn-api"></a>
### `api()`

```php
function api($viewData = array())
```

Generic view function that instantiates a View class

**Parameters**

+ `$viewData`, default `array()`

Source: [framework/helpers/corehelpers.php:298](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L298)

<a name="fn-findkey"></a>
### `findKey()`

```php
function findKey($array, $keySearch)
```

Looks for a key in a multidimensional array

**Parameters**

+ `$array` `array`: define the array to be searched
+ `$keySearch` `string`: defines the key to be searched

**Returns** `boolean`: if at least one instance is found

Source: [framework/helpers/corehelpers.php:312](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L312)

<a name="fn-recursive-filter"></a>
### `recursive_filter()`

```php
function recursive_filter(&$array, $allowed)
```

Filters the result depending on package chosen

**Parameters**

+ `$array` `int`: defines the array to be filtered
+ `$allowed` `array`: defines what the package allows

**Returns** `array`: the filtered results

Source: [framework/helpers/corehelpers.php:337](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L337)

<a name="fn-loadconstantfromarray"></a>
### `loadConstantFromArray()`

```php
function loadConstantFromArray($array)
```

Define constants from 2D array

**Parameters**

+ `$array` `array`: defines the array to turn into constant definition

**Returns** `boolean`: if action was executed

Source: [framework/helpers/corehelpers.php:359](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L359)

<a name="fn-terminatesession"></a>
### `terminateSession()`

```php
function terminateSession($url)
```

Terminates a session

**Parameters**

+ `$url`: to redirect the user upon session termination

Source: [framework/helpers/corehelpers.php:378](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L378)

<a name="fn-getglobalinformation"></a>
### `getGlobalInformation()`

```php
function getGlobalInformation($superGlobal = 'session')
```

Function that gets all the super global variables needed for a page to function

**Parameters**

+ `$superGlobal` `string`, default `'session'`: determines which super variable to fetch information from

**Returns** `array`: $result returns an array of all the fetched information desired

Source: [framework/helpers/corehelpers.php:396](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L396)

<a name="fn-isallowedupload"></a>
### `isAllowedUpload()`

```php
function isAllowedUpload($filename, $allowedExtensions = null)
```

Checks if a file name has an extension that can safely be uploaded

**Parameters**

+ `$filename` `string`: the original file name
+ `$allowedExtensions` `array`, default `null`: the allowed extensions. Defaults to DEFAULT_UPLOAD_EXTENSIONS

**Returns** `boolean`: true if the extension is allowed

Source: [framework/helpers/corehelpers.php:438](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L438)

<a name="fn-uploadfile"></a>
### `uploadFile()`

```php
function uploadFile($picture, $allowedExtensions = null)
```

Uploads a file from a form into the server

**Parameters**

+ `$picture` `array`: defines the file attributes array (an entry of $_FILES)
+ `$allowedExtensions` `array`, default `null`: the allowed extensions. Defaults to DEFAULT_UPLOAD_EXTENSIONS

**Returns** `string`: the resulting public URL of the uploaded file, or '' if the file was refused or could not be moved

Source: [framework/helpers/corehelpers.php:455](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L455)

<a name="fn-deletefile"></a>
### `deleteFile()`

```php
function deleteFile($url)
```

Deletes a file given its public path

**Parameters**

+ `$url` `string`: of the image public url

**Returns** `boolean`: of the result

Source: [framework/helpers/corehelpers.php:491](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L491)

<a name="fn-isjson"></a>
### `isJson()`

```php
function isJson($string)
```

Checks if a string is a json

**Parameters**

+ `$string` `string`: defines the string to be checked

**Returns** `boolean`: true if it is a json

Source: [framework/helpers/corehelpers.php:511](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L511)

<a name="fn-sanitize"></a>
### `sanitize()`

```php
function sanitize($string)
```

Sanitizes a string from html tags

**Parameters**

+ `$string` `string`: defines the string to be sanitized

**Returns** `string`: the sanitized screen

Source: [framework/helpers/corehelpers.php:526](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L526)

<a name="fn-request"></a>
### `request()`

```php
function request()
```

Accessor to the request information

**Returns** `Request`: the request object information

Source: [framework/helpers/corehelpers.php:539](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L539)

<a name="fn-connect"></a>
### `connect()`

```php
function connect()
```

Accessor connects a controller to the model

**Returns** `Model`: with connection to database established

Source: [framework/helpers/corehelpers.php:552](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L552)

<a name="fn-import"></a>
### `import()`

```php
function import($filename)
```

Accessor to require more librairies and helpers classes and files

**Parameters**

+ `$filename`

Source: [framework/helpers/corehelpers.php:564](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L564)

<a name="fn-parsepath"></a>
### `parsePath()`

```php
function parsePath($path)
```

_No doc comment._

**Parameters**

+ `$path`

Source: [framework/helpers/corehelpers.php:577](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L577)

<a name="fn-currentroute"></a>
### `currentRoute()`

```php
function currentRoute()
```

Accessor to the route information

**Returns** `String`: the route information

Source: [framework/helpers/corehelpers.php:591](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L591)

<a name="fn-currentbind"></a>
### `currentBind()`

```php
function currentBind()
```

Accessor to the list of variables bound to the route

**Returns** `Array`: bound variables from the route

Source: [framework/helpers/corehelpers.php:602](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L602)

<a name="fn-startwith"></a>
### `startWith()`

```php
function startWith($haystack, $needle)
```

Checks if strings starts with a character and removes it

**Parameters**

+ `$haystack`
+ `$needle`

**Returns** `String`: with the character removed

Source: [framework/helpers/corehelpers.php:613](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L613)

<a name="fn-endwith"></a>
### `endWith()`

```php
function endWith($haystack, $needle)
```

Checks if strings ends with a character and removes it

**Parameters**

+ `$haystack`
+ `$needle`

**Returns** `String`: with the character removed

Source: [framework/helpers/corehelpers.php:624](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L624)

<a name="fn-sanitizepath"></a>
### `sanitizePath()`

```php
function sanitizePath($path)
```

Sanitizes the path by getting rid of beginning and ending slashes

**Parameters**

+ `$path`

**Returns** `String`: the new path without the slashes

Source: [framework/helpers/corehelpers.php:636](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L636)

<a name="fn-associate"></a>
### `associate()`

```php
function associate($controller, $modelname, $table)
```

_No doc comment._

**Parameters**

+ `$controller`
+ `$modelname`
+ `$table`

Source: [framework/helpers/corehelpers.php:643](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L643)

<a name="fn-bindroutetovar"></a>
### `bindRouteToVar()`

```php
function bindRouteToVar($route, $uri, $pattern = ROUTE_ARG_PATTERN)
```

_No doc comment._

**Parameters**

+ `$route`
+ `$uri`
+ `$pattern`, default `ROUTE_ARG_PATTERN`

Source: [framework/helpers/corehelpers.php:648](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L648)

<a name="fn-parseroute"></a>
### `parseRoute()`

```php
function parseRoute($path, $pattern = ROUTE_ARG_PATTERN)
```

Parses a path

**Parameters**

+ `$path`
+ `$pattern`, default `ROUTE_ARG_PATTERN`

**Returns** `parsed`: information

Source: [framework/helpers/corehelpers.php:672](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L672)

<a name="fn-require-all"></a>
### `_require_all()`

```php
function _require_all($path, $depth = 0)
```

load all files in user-created directories and subdirectories

**Parameters**

+ `$path`
+ `$depth`, default `0`

Source: [framework/helpers/corehelpers.php:689](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L689)

<a name="fn-singularize"></a>
### `singularize()`

```php
function singularize($word)
```

Singularizes regular plurals

**Parameters**

+ `$word`

Source: [framework/helpers/corehelpers.php:712](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L712)

<a name="fn-methodfield"></a>
### `methodField()`

```php
function methodField($method)
```

Injects a hidden html input to change the method

**Parameters**

+ `$method`

Source: [framework/helpers/corehelpers.php:722](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L722)

<a name="fn-csrf"></a>
### `csrf()`

```php
function csrf()
```

Injects a csrf field into the form

Source: [framework/helpers/corehelpers.php:732](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L732)

<a name="fn-errors"></a>
### `errors()`

```php
function errors($field = null)
```

The field errors a Route::form() sent back with the previous request (2.19.0): all of them, or one field's message
(null when it has none). In a view: if errors('title') / p.cq-field-error= errors('title')

**Parameters**

+ `$field`, default `null`

Source: [framework/helpers/corehelpers.php:741](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L741)

<a name="fn-old"></a>
### `old()`

```php
function old($field, $default = '')
```

What a field held when a Route::form() sent it back (2.19.0), else $default: input(name='title', value=old('title'))
Passwords and other secrets are never kept.

**Parameters**

+ `$field`
+ `$default`, default `''`

Source: [framework/helpers/corehelpers.php:751](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L751)

<a name="fn-flash"></a>
### `flash()`

```php
function flash($key, $value = null)
```

A message of the previous request (2.19.0): flash('success') after a Route::form() 'flash', flash('error') after
invalid input; with a value, keeps a message for the next request

**Parameters**

+ `$key`
+ `$value`, default `null`

Source: [framework/helpers/corehelpers.php:761](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L761)

<a name="fn-authorize"></a>
### `authorize()`

```php
function authorize($user)
```

Method that authorizes a logged in user to perform actions

**Parameters**

+ `$user`

Source: [framework/helpers/corehelpers.php:776](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L776)

<a name="fn-authorized"></a>
### `authorized()`

```php
function authorized()
```

Method that checks if a session user is allowed to perform actions

Source: [framework/helpers/corehelpers.php:786](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L786)

<a name="fn-unauthorize"></a>
### `unauthorize()`

```php
function unauthorize()
```

Method used upon logout to unauthorize a user in session from performing actions

Source: [framework/helpers/corehelpers.php:796](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L796)

<a name="fn-user"></a>
### `user()`

```php
function user()
```

Method that retrieves the user currently logged in

Source: [framework/helpers/corehelpers.php:806](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L806)

<a name="fn-guard"></a>
### `guard()`

```php
function guard(
    $permissionAttribute,
    $acceptedPermission,
    $loginUrl = '/login',
    $notAuthorized = '/notAuthorized'
)
```

Method that checks if the user in session has permissions to access

**Parameters**

+ `$permissionAttribute`
+ `$acceptedPermission`
+ `$loginUrl`, default `'/login'`
+ `$notAuthorized`, default `'/notAuthorized'`

**Returns** `boolean`: of whether or not the user is valid and allowed to perform actions

Source: [framework/helpers/corehelpers.php:815](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L815)

<a name="fn-logout"></a>
### `logout()`

```php
function logout($redirectUrl = '/')
```

Method that logs the user out

**Parameters**

+ `$redirectUrl`, default `'/'`

Source: [framework/helpers/corehelpers.php:823](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L823)

<a name="fn-imagecanva"></a>
### `imageCanva()`

```php
function imageCanva()
```

Method that instantiates the Claviska Simple Image library that manipulate pictures

Source: [framework/helpers/corehelpers.php:834](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L834)

<a name="fn-load-script"></a>
### `load_script()`

```php
function load_script($params)
```

Loads a script into the UI

**Parameters**

+ `$params` `array`: inputs needed to generate the script

**Returns** `string`: HTML or TXT fully formatted

Source: [framework/helpers/corehelpers.php:854](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L854)

<a name="fn-redirect"></a>
### `redirect()`

```php
function redirect($url)
```

Reroutes to another url

**Parameters**

+ `$url`

Source: [framework/helpers/corehelpers.php:874](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L874)

<a name="fn-getrelativetime"></a>
### `getRelativeTime()`

```php
function getRelativeTime($datetime, $depth = 1)
```

Get RelativeTime

**Parameters**

+ `$datetime`
+ `$depth`, default `1`

Source: [framework/helpers/corehelpers.php:891](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L891)

<a name="fn-rearrange"></a>
### `rearrange()`

```php
function rearrange($arr)
```

Rearrange multi-dimensional array onto key array. Used to rearrange File inputs

**Parameters**

+ `$arr`

Source: [framework/helpers/corehelpers.php:947](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L947)

<a name="fn-httpfile"></a>
### `httpFile()`

```php
function httpFile($url, $filepath, $headers, $username = null, $password = null, $purpose = 'assistants')
```

cUrl post file function

**Parameters**

+ `$url`
+ `$filepath`
+ `$headers`
+ `$username`, default `null`
+ `$password`, default `null`
+ `$purpose`, default `'assistants'`

Source: [framework/helpers/corehelpers.php:959](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L959)

<a name="fn-httprequest"></a>
### `httpRequest()`

```php
function httpRequest($url, $method, $data, $headers, $username = null, $password = null)
```

cUrl request function

**Parameters**

+ `$url`
+ `$method`
+ `$data`
+ `$headers`
+ `$username`, default `null`
+ `$password`, default `null`

Source: [framework/helpers/corehelpers.php:998](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L998)

<a name="fn-now"></a>
### `now()`

```php
function now()
```

now() returns the current timestamp in a mySQL format

Source: [framework/helpers/corehelpers.php:1038](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L1038)

<a name="fn-sendmail"></a>
### `sendMail()`

```php
function sendMail($recipients, $emailContent, $from)
```

sendMail() sends an email using the configuration in the .env file

**Parameters**

+ `$recipients` `array`: : array('email' =&gt; 'recipient_email', 'name' =&gt; 'recipent_name)
+ `$emailContent`
+ `$from`

Source: [framework/helpers/corehelpers.php:1049](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L1049)

<a name="fn-arraysort"></a>
### `arraySort()`

```php
function arraySort($array, $attribute, $sort = SORT_DESC)
```

arraySort() sorts a multimdimensional array by a column

**Parameters**

+ `$array` `array`: defines the  array to sort
+ `$attribute` `string`: defines the column to sort by
+ `$sort` `string`, default `SORT_DESC`: defines the sorting direction: SORT_ASC, SORT_DESC

**Returns** `array`: sorted array

Source: [framework/helpers/corehelpers.php:1063](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/helpers/corehelpers.php#L1063)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer -->

**Caligrafer** is the command line tool of Caligrafy: `caligrafer.php` at the root of every project, and the shell launcher `.bin/caligrafer`. It sets a project up, creates capabilities and client apps, runs SQL and migrations, manages the tokens of programs and AI agents, runs jobs and tests, checks the project, updates it, and puts it online. This page lists every command, with the usage text the command prints.

**Since 2.26.0**: `php caligrafer.php add <payments | ai | push | passkeys | snap | async | facedetect>` (an optional feature's SDK or files), `optimize` (every view compiled and the class map built, as the production image does at start) and `async <check | start>` (the experimental async server).
## With Claude

The plugin's skills run Caligrafer for you: `/caligrafy-quill:server` (the Docker server), `/caligrafy-quill:db` (`sql`, `migrate`), `/caligrafy-quill:new-capability` (`service`, `client`, `token`, `call`), `/caligrafy-quill:update` (`update`, `upgrade`), `/caligrafy-quill:ship` and `/caligrafy-quill:deploy` (`cloud`). Ask in plain words, for example "list my capabilities" or "create a token for my agent with books:read": Claude runs the command and shows the output, never a secret it does not have to.

## By hand

Open a terminal in the project folder and run, for example:
```bash
docker compose exec dev-box php caligrafer.php capabilities
```
It prints one line per capability: its name, who may call it, whether it reads, writes or destroys, and its description.
## <a name="run"></a>How to run it

| Where PHP runs | Run Caligrafer with |
| --- | --- |
| **Docker** (the Quickstart) | `docker compose exec dev-box php caligrafer.php <command>`; add `-T` when the output goes to a file or a script |
| Your own PHP 8.3+ | `php caligrafer.php <command>`, in the project folder |
| Either, for setting up and the server | `.bin/caligrafer <command>`: see [`.bin/caligrafer`](#bin) |

`php caligrafer.php` with no command, or with a command it does not know, prints the list of commands. Except `version` and `doctor`, every command first creates `.env` from `framework/settings/.env.example` when it is missing. Any command reads another environment file with `--env <file>` (for example `php caligrafer.php sql application/models/Bookshelf/create_db.sql --env .env.testing`); a file that does not exist prints `Environment file not found: <file>` and exits with `1`. In the rest of this page, `php caligrafer.php` means the first two forms.
## <a name="map"></a>Every command

| Command | What it does |
| --- | --- |
| [`quickstart`](#quickstart) | Sets a project up in one step (Docker, MAMP, XAMPP or LAMP); `--example` adds the Tasks example |
| [`initialize`](#initialize) | Prepares a fresh copy of the framework: `application/`, `.env`, keys |
| [`created`](#created) | Run by Composer after `composer create-project`: says the next command |
| [`server`](#server) | Starts, stops or rebuilds the Docker development server |
| [`version`](#version) | Prints the version of Caligrafy Quill |
| [`doctor`](#doctor) | Read-only health check of the project and its services |
| [`design`](#design) | Picks a design style for every page (`DESIGN_STYLE`) |
| [`service`](#service) | Creates a capability in `application/services/` |
| [`capabilities`](#capabilities) | Lists the capabilities |
| [`call`](#call) | Calls a capability and prints its JSON answer |
| [`client`](#client) | Writes the JavaScript client of the capabilities |
| [`app`, `create`, `facedetect`, `ml`, `bot`](#apps) | Creates a client app in `public/` |
| [`sql`](#sql) | Runs a SQL script on the database |
| [`migrate`](#migrate) | Runs, lists or writes migrations |
| [`platform install`](#platform) | Creates the framework tables |
| [`snap`](#snap) | Snap Cards and the assistant: its tables, a starter hints file, what is ready |
| [`token`](#token) | Creates, lists and revokes personal access tokens |
| [`mcp`](#mcp) | An MCP server over stdio, for AI agents on this computer |
| [`audit`](#audit) | The latest capability calls and refusals |
| [`schedule`](#schedule) | Scheduled jobs: list, run, history |
| [`queue`](#queue) | Background jobs: work, list, retry |
| [`notify`](#notify) | Web push keys, and a test notification |
| [`test`](#test) | Runs the app's tests, or writes one |
| [`cache clear`](#cache) | Empties the cache, the compiled views and the class map |
| [`env`](#env) | Compiles `.env` to `.env.php`, or removes it |
| [`update`](#update) | Moves the project to another release of Caligrafy Quill |
| [`upgrade`](#upgrade) | Updates the untouched files of `application/` to the framework's templates |
| [`plugin`](#plugin) | Connects the project's Claude Code plugin to Claude Code |
| [`deploy`](#deploy) | Prepares the database in production (the production image runs it) |
| [`cloud`](#cloud) | Puts the project online with Caligrafy Cloud |
| [`generatekeys`, `generateapikey`](#keys) | Generates application keys and legacy API keys |
## Set up a project

### <a name="quickstart"></a>`quickstart`
```text
quickstart [--example] [--yes]: sets up a fresh project in one step (database, framework tables, /capabilities and /mcp); --example adds the Tasks example. With Docker: .bin/caligrafer quickstart
```
```bash
.bin/caligrafer quickstart --docker --example        # Docker (the Quickstart)
.bin/caligrafer quickstart --local --example         # MAMP, XAMPP or LAMP
php caligrafer.php quickstart --example --yes --url http://localhost/myapp   # your own PHP (Windows too)
```
| Option | Effect |
| --- | --- |
| `--example` | adds the Tasks example: five capabilities, a model, a page, the `tasks` table, its routes, `public/js/capabilities.js` |
| `--yes` | allows `initialize` to delete the framework's `.git` (`.bin/caligrafer` asks instead) |
| `--docker`, `--local` | (`.bin/caligrafer` only) the server; without them: the local server when Apache (`httpd` or `apache2`) runs and PHP is installed, else Docker |
| `--url <address>` | the address of the project on a local server, when it is not in a known web folder |
| `--no-db` | skips the database steps |
| `--db-defaults` | without a terminal, uses the local server's MySQL defaults instead of skipping the database |

Steps, each run only when needed: `initialize` (refused without `--yes` when a `.git` exists); with Docker, `DB_ACTIVATE=true`, `DB_HOST=mysql` and `DB_DATABASE=caligrafy` in `.env`; on a local server, `APP_ROOT` from the project's place in the web folder (MAMP's settings are read) and the MySQL settings asked with the server's defaults; the database (`CREATE DATABASE IF NOT EXISTS`) and `platform install`; `Route::capabilities('/capabilities')`, `Route::mcp('/mcp')` and `Route::notifications()` above `Route::run()` in `web.php`; the example. A local MySQL that does not answer sets `DB_ACTIVATE=false` again. It never overwrites a file. The output is shown in the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart).

### <a name="initialize"></a>`initialize`
```text
initialize: Initializes and signs your project
```
```bash
php caligrafer.php initialize            # APP_ROOT=<folder name>: the site is at http://localhost/<folder>/
php caligrafer.php initialize off        # APP_ROOT empty: the site is at the root (Docker)
php caligrafer.php initialize --yes      # also deletes .git without asking
```
```text
Preparing and signing the project for usage... 

 Contributor skill removed (.claude/skills/caligrafy-contributor: for the framework repository only)
 Claude Code plugin source: caligrafy-myapp-b6ea (enable caligrafy-quill@caligrafy-myapp-b6ea when Claude Code asks)
 .git kept (php caligrafer.php initialize --yes deletes it)
 Application initialized successfully
 APP_KEY=...
 API_KEY=...
```
It writes `APP_KEY` and `API_KEY` to `.env` (a project that has both keeps them: `Existing APP_KEY and API_KEY kept`), sets `APP_ROOT`, writes `framework/librairies/app/.env` for the Vue SPA template, copies `framework/settings/application` to `application/` when it does not exist (with `application/.caligrafy-manifest.json`, which [`upgrade`](#upgrade) reads), makes `public/uploads` writable, removes the contributor skill, and gives the project's Claude Code plugin source its own name. In a terminal it asks before deleting `.git`; without a terminal it keeps it. `quickstart` runs it for you.

### <a name="created"></a>`created`
Run by Composer at the end of `composer create-project caligrafy/caligrafy-quill <folder>`. It prints the folder, the next command (`.bin/caligrafer quickstart --example`, or `php caligrafer.php quickstart --example` on Windows), the address on a running MAMP, XAMPP or LAMP, and whether Docker is running. You do not run it yourself.

### <a name="server"></a>`server`
```text
server <start | stop | rebuild>: Starts a Caligrafy local LAMP server with phpmyadmin (requires PHP, Composer and Docker); rebuild updates the server image
```
```bash
.bin/caligrafer server start      # docker compose up -d dev-box scheduler
.bin/caligrafer server stop       # docker compose stop
.bin/caligrafer server rebuild    # docker compose build --pull dev-box, then up -d dev-box
```
```text
Caligrafy Server successfully started.

 Hostname: http://localhost:8080
 phpmyadmin: http://localhost:8077
 mysql: localhost:3306 (from your computer; mysql:3306 from the containers)
 mysql username: root 
 mysql password: root 
```
The Docker server is `dev-box` (PHP 8.5 and Apache, your folder mounted in it), `mysql` (MySQL 8.4), `phpmyadmin` (5.2.3) and `scheduler` (runs [`schedule work`](#schedule)). The first start builds the PHP image; later starts take seconds; `rebuild` rebuilds it after a change to `docker/Dockerfile`. The ports are the ones Docker published, so a `docker-compose.override.yml` that moves them (another project holds 8080) is followed: `Hostname: http://localhost:8170` with `"8170:80"` in it (2.24.0; when the containers are not running, the compose files and their override say). `php caligrafer.php server start` works by hand too (2.24.0); when a local Apache is running, `.bin/caligrafer server start` uses that server and says so. Without `.bin/caligrafer`: `docker compose up -d dev-box` and `docker compose stop`.

### <a name="bin"></a>`.bin/caligrafer`
```bash
.bin/caligrafer quickstart [--docker | --local] [quickstart options]
.bin/caligrafer <command> [options]
```
+ `quickstart`: chooses the server, asks before deleting `.git`, installs the PHP libraries when `vendor/` is missing (your Composer, else the `composer:2` image), starts `dev-box` and runs `php caligrafer.php quickstart` in it (Docker), or runs it with your PHP (local). It then registers the project's Claude Code plugin when the `claude` command is installed.
+ Any other command: with PHP and Composer on the computer, it runs `./caligrafer.php <command>` with your arguments (`initialize` and `server` get `off` added when no local Apache runs). A folder without `application/` or `.env` only accepts `initialize`, `version`, `doctor` and `update`.
+ Without PHP or Composer, it runs `.bin/server start|stop`: the `prod-box` container, with the code copied into the image, at `http://localhost:8080/caligrafy-quill`.

### <a name="version"></a>`version`
```bash
php caligrafer.php version        # also --version and -v
```
```text
Caligrafy Quill 2.25.0
```
It works before `composer install` and never creates `.env`. In code: `Caligrafy\Framework::VERSION`. The changes of every version are in the [changelog](https://github.com/caligrafy/caligrafy-quill/blob/master/CHANGELOG.md).
## Build features

### <a name="service"></a>`service`
```text
 Usage: php caligrafer.php service <Name> [--scope <resource:action>] [--read-only]
 Name in PascalCase, optionally in folders: Books/CreateBook
```
```bash
php caligrafer.php service Bookshelf/CreateBook --scope books:write
php caligrafer.php service Bookshelf/ListBooks --scope books:read --read-only
```
```text
 Created application/services/Bookshelf/CreateBook.php: capability 'create_book' (scope books:write)
 Fill in $rules and handle(), then serve it: a page (Route::page data), a form (Route::form), REST (Route::capability or Route::capabilities), MCP (Route::mcp)
```
For a [web-only capability](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#webonly), add `webOnly: true` to its attribute by hand. The capability's name is the snake_case of the class name. Always give `--scope`: without it the capability needs no scope, and any token can call it. It refuses to overwrite a file, and needs `application/`. Fill the class as [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability#capabilities) shows.

### <a name="capabilities"></a>`capabilities`
```text
capabilities [--json | --markdown]: the capabilities of application/services/ (what REST, MCP and the JS client can call)
```
```bash
php caligrafer.php capabilities              # one line each
php caligrafer.php capabilities --markdown   # a table for your documentation
php caligrafer.php capabilities --json       # with the input schemas
```
```text
 create_book                  books:write    writes    Adds a book to the Bookshelf catalog and returns it with its id and its author. The author must already exist: use list_authors to find author_id. The ISBN is optional and unique.
 get_book                     public         read      Returns one book of the catalog with its author (id, name, bio), by the id of the book.
```
The columns: the name; who may call it (`public`, the scope, or `signed in` when it has no scope); `read`, `writes` or `destroys`; the description. The framework's own capabilities (users, notifications, `queue_work`) are listed too.

### <a name="call"></a>`call`
```text
 Usage: php caligrafer.php call <capability> ['{"key": "value"}' | key=value ...] [--token <token>] [--guest]
 Lists the capabilities: php caligrafer.php capabilities
```
```bash
php caligrafer.php call list_books
php caligrafer.php call get_book id=3
php caligrafer.php call create_book '{"title": "Dawn", "published_year": 1987, "author_id": 2}'
php caligrafer.php call create_book title=Dawn published_year=1987 author_id=2 --guest          # as a visitor who is not signed in
php caligrafer.php call create_book title=Dawn published_year=1987 author_id=2 --token cq_...   # as a token (or CALIGRAFY_TOKEN=cq_...)
```
It prints the same JSON as REST: `{"data": ...}` with exit code `0`, or `{"error": {"code": "invalid", "message": "...", "fields": {...}}}` with exit code `1`. Without `--token` or `--guest` it has full access, like any script you run (channel `cli` in the audit log).

### <a name="client"></a>`client`
```text
client [<file>] [--prefix /capabilities]: writes the JS client of the capabilities (default public/js/capabilities.js)
```
```bash
php caligrafer.php client                                   # public/js/capabilities.js
php caligrafer.php client public/myspa/src/capabilities.js  # a single page application
php caligrafer.php client --prefix /api/capabilities        # Route::capabilities('/api/capabilities')
```
```text
 public/js/capabilities.js written: 21 capabilities, calls /capabilities (Route::capabilities('/capabilities') in web.php)
 import { createBook, CapabilityError } from './capabilities.js'
```
One function per capability (`create_book` becomes `createBook`), plus `call(name, input)`, `capabilities()`, `configure({ baseUrl, token, prefix, credentials })` and `CapabilityError` (`status`, `code`, `fields`). In a page of the application it sends the visitor's session and CSRF token. Run it again after every change to a capability. Learn more in [the JS client](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#client).

### <a name="apps"></a>`app`, `create`, `facedetect`, `ml`, `bot`
```text
create <project_name>: scaffolds a Vue project
app <project_name>: scaffolds a regular Client HTML/JS project
bot <bot_name>: creates a bot application
facedetect <app_name>: creates a face detection application
ml <app_name>: creates an ml powered application
```
```bash
php caligrafer.php app catalog         # Vue 3 as a library:            http://localhost:8080/apps/catalog
php caligrafer.php create myspa        # a Vite Vue single page application (Node.js 20.19+ or 22.12+)
php caligrafer.php facedetect faces    # face detection:                 http://localhost:8080/apps/faces
php caligrafer.php ml lab              # machine learning in the browser: http://localhost:8080/ml/lab
php caligrafer.php bot helper          # a Watson chatbot:               http://localhost:8080/bot/helper?botSkillId=<id>
```
```text
 Project created in the public folder.
 Type cd public/catalog to access it anytime
```
Each one copies a template into `public/<name>` (`create`: `framework/librairies/app`; the others: `framework/plugins/<type>`). The name cannot be `app`, `bot`, `__bots__`, `css`, `facedetect`, `fonts`, `images`, `js`, `ml`, `resources` or `uploads`. `create` (2.19.1) gives a single page application that calls the application with the visitor's session: no API key in the bundle, `apiHeaders()` of `src/common/app.js` adds the `X-CSRF-Token` header, hash history (`#/page`), `base: './'` in `vite.config.js`, and `dist/` is committed (the production image does not run `npm`). It also runs `npm install` when `npm` is available; the Docker `dev-box` has no Node.js, so it says the packages are not installed: run `npm install` in `public/<name>` on your computer, then `npm run dev`. Learn more: [Vue as a library](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.0-Setting-up-Vue.js-as-a-library), [the single page application](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.1---Setting-up-the-Vue-application), [face detection](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition), [machine learning](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.3-Machine-Learning), [chatbots](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.1-Creating-Bots-with-Watson).
## Data

### <a name="sql"></a>`sql`
```text
 Usage: php caligrafer.php sql <file.sql>
```
```bash
php caligrafer.php sql application/models/Bookshelf/create_db.sql
```
```text
 application/models/Bookshelf/create_db.sql run on caligrafy
```
Runs a SQL script on the database of `.env` (`DB_ACTIVATE=true`): `/* */` and `--` comments removed, the statements run one by one. A failure prints `<file> could not be run: <reason>` and exits with `1`. It creates the tables of a new database; a change to a table that holds data is a [migration](#migrate).

### <a name="migrate"></a>`migrate`
```text
 Usage: php caligrafer.php migrate [status | make <name>] [--env <file>]
 Runs the migrations of application/migrations that never ran on this database
```
```bash
php caligrafer.php migrate make add_books_isbn   # writes application/migrations/<YmdHis>_add_books_isbn.sql
php caligrafer.php migrate                       # runs the ones that never ran, in order
php caligrafer.php migrate status                # ran, pending or changed
php caligrafer.php migrate --env .env.testing    # on the database of another environment file (2.19.1)
```
```text
 OK   20261107232335_add_books_isbn.sql

 1 migration(s) run on caligrafy
```
Then `Nothing to migrate: caligrafy is up to date`. `--env <file>` can come anywhere after `migrate` (`migrate status --env .env.testing`); before 2.19.1 it was read as the sub-command. Each file runs once and is recorded in `caligrafy_migrations`; a file edited after it ran shows `changed` and never runs again: write a new one. `make` needs no database. [`deploy`](#deploy) runs the pending ones online. Learn more in [Migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations).

### <a name="platform"></a>`platform install`
```text
 Usage: php caligrafer.php platform install
 Creates the framework tables (tokens, audit log, job runs, notifications, jobs, cache, migrations, Snap) from framework/settings/platform.sql
```
```bash
php caligrafer.php platform install
```
```text
 Framework tables ready: caligrafy_tokens, caligrafy_audit, caligrafy_job_runs, the notifications tables, caligrafy_jobs, caligrafy_cache, caligrafy_migrations and Snap's tables
```
Safe to run again. `quickstart` and `deploy` run it; `doctor` says when the tables are missing.

### <a name="snap"></a>`snap`
```bash
php caligrafer.php snap install   # Snap's tables, and application/config/snap.php when there is none
php caligrafer.php snap           # what is ready (snap status)
php caligrafer.php snap views     # each card that shows data: its card view, stale ones, or a designed card (2.25.0)
```
```text
 Snap Cards and the assistant
  [ok] Tables            caligrafy_snap_*
  [ok] Route             Route::snap(); in application/config/routing/web.php
  [ok] Card hints        application/config/snap.php (optional: cards work without it)
  [ok] Background tasks  the queue runs them: ...
  [ok] Routines          ... snap_routines_due ...
  [--] Assistant model   ANTHROPIC_API_KEY in .env (without it the assistant answers from the cards' names)
```
```text
 Card views (application/views/snap/<capability>.pug)
  [ok] get_book                   from Bookshelf/book.pug
  [!!] list_books                 Bookshelf/books.pug changed since its card view was made: write it again
  [--] get_user                   no card view: a card designed from its data
```
`snap views` exits 1 when a card view is stale. Since 2.23.0 (`views` since 2.25.0). See
[Snap Cards and the assistant](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant#looks).

### <a name="cache"></a>`cache clear`
```text
 Usage: php caligrafer.php cache clear
 Empties the cache (Caligrafy\Cache, CACHE_STORE in .env), the compiled views and the class map
```
```text
 Cache (database) emptied; 2 compiled view and class map file(s) removed
```
See [Caching](https://github.com/caligrafy/caligrafy-quill/wiki/Caching).

### <a name="env"></a>`env`
```text
 Usage: php caligrafer.php env <cache | clear>
```
```bash
php caligrafer.php env cache    # .env compiled to .env.php: pages read it without parsing .env (php caligrafer.php env clear removes it)
php caligrafer.php env clear    # .env.php removed: pages read .env again
```
Pages read `.env.php` instead of parsing `.env` on every request, as long as `.env` is exactly what it was compiled from (its content is compared, not its date): edit `.env` and pages read it again at once. [`deploy`](#deploy) runs `env cache` at every start in production. `.env.php` holds the same secrets as `.env` and is in `.gitignore`: never commit it. `env cache` exits with `1` when there is no `.env`.
## Programs and AI agents

### <a name="token"></a>`token`
```text
 Usage:
 php caligrafer.php token create <name> --scopes <a:read,b:write | *> [--user <id>] [--expires <days>]
 php caligrafer.php token list
 php caligrafer.php token revoke <id>
```
```bash
php caligrafer.php token create "books agent" --scopes books:read,books:write
php caligrafer.php token create "Reporting job" --scopes books:read --expires 90
php caligrafer.php token create "Sam's agent" --scopes "books:*" --user 7
php caligrafer.php token list
php caligrafer.php token revoke 2
```
```text
 Token #2 "books agent" created with books:read books:write

 cq_2_...

 It is shown only now: store it as a secret (Authorization: Bearer <token>).
```
```text
 #2    active   books agent                    books:read books:write  last used 2026-11-07 23:17:49
```
+ `--scopes` (required): `resource:action` values separated by commas; `books:*` for every action on books; `*` for everything.
+ `--expires <days>`: the token stops working after that many days.
+ `--user <id>`: the token acts for that user, so a capability's `level` applies to them.

Only the token's hash is kept. `revoke` takes the number without `#` and stops the token at once. It needs the framework tables. Learn more in [Personal access tokens](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#tokens).

### <a name="mcp"></a>`mcp`
```text
mcp [--token <token>]: MCP server over stdio for local AI agents (Claude Code, Cursor...): php caligrafer.php mcp
```
```bash
claude mcp add myapp -- php caligrafer.php mcp                                  # your own PHP
claude mcp add myapp -- docker compose exec -T dev-box php caligrafer.php mcp   # Docker
```
One JSON-RPC message per line on standard input, one answer per line on standard output. Without a token it has full access and prints `caligrafer mcp: no token, full local access (set CALIGRAFY_TOKEN to limit it)` on standard error; with `CALIGRAFY_TOKEN` (or `--token <token>`) it sees only what the token allows. For agents that reach the application over the network, use `Route::mcp('/mcp')` and a token: see [AI agents: MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#mcp).

### <a name="audit"></a>`audit`
```text
audit [--limit 50] [--capability <name>]: the latest capability calls
```
```bash
php caligrafer.php audit
php caligrafer.php audit --capability create_book --limit 200
```
```text
 2026-11-07 23:17:49  rest  token  2            create_book                  ok
 2026-11-07 23:17:49  rest  guest  -            create_book                  unauthenticated  Sign in or send a personal access token
```
When, the channel (`web`, `rest`, `mcp`, `cli`), the caller (`user`, `token`, `key`, `cli`, `guest`, or the system of a job, with its id), the capability, the outcome and its detail. Every change and every refusal is recorded; successful reads and inputs are not.
## Jobs and tests

### <a name="schedule"></a>`schedule`
```text
 Usage: php caligrafer.php schedule <list [--json] | run <job> | due | work | history [<job>] [--limit 50]>
 Jobs are declared in application/config/schedule.php
```
```bash
php caligrafer.php schedule list                # checks schedule.php and lists the jobs (--json: what Caligrafy Cloud reads)
php caligrafer.php schedule run check-prices    # one job now (--if-due: only when it is due this minute)
php caligrafer.php schedule due                 # the jobs due this minute
php caligrafer.php schedule work                # every minute until stopped (the scheduler container runs it)
php caligrafer.php schedule history             # the latest runs ([<job>] [--limit 50])
```
With no `application/config/schedule.php`: `No scheduled jobs (application/config/schedule.php declares them)`. Exit codes: `0` ok, `1` a job failed or timed out, `2` the file is invalid, `3` skipped (still running). Learn more in [Scheduled jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs).

### <a name="queue"></a>`queue`
```text
 Usage: php caligrafer.php queue <work [--queue default] [--for <seconds>] [--once] [--sleep 3] | status | list [--status failed] [--limit 50] | failed | retry <id | all>>
 Background jobs pushed with Caligrafy\Queue::push('<capability>', [...])
```
```bash
php caligrafer.php queue work --once      # what is due, then stops
php caligrafer.php queue work --for 300   # for 5 minutes; without --once or --for: until Ctrl+C
php caligrafer.php queue status
php caligrafer.php queue list --status failed
php caligrafer.php queue retry 42         # retry all: every failed job
```
```text
 Working the queue default until it is empty
 0 done, 0 to try again, 0 failed
```
`status` prints `0 pending, 0 running, 0 done, 0 failed`. Each job runs in its own process (`queue exec <id>`, internal), stopped at its timeout, and tried again when it fails. Online, a scheduled job on `queue_work` runs them. Learn more in [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs).

### <a name="notify"></a>`notify`
```text
 Usage: php caligrafer.php notify <keys [--subject mailto:you@example.com] | test <user id> | status <user id>>
```
```bash
php caligrafer.php notify keys --subject mailto:you@example.com   # the web push keys, once
php caligrafer.php notify test 7                                  # a test notification to user 7
php caligrafer.php notify status 7                                # user 7's channels
```
`keys` writes `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` and `VAPID_SUBJECT` to `.env` and refuses to replace them (new keys cut off every subscribed browser). Without `--subject` it uses `MAIL_FROM` or `MAIL_USERNAME` when it is an address, else `APP_URL`. Learn more in [Notifications](https://github.com/caligrafy/caligrafy-quill/wiki/Notifications).

### <a name="test"></a>`test`
```text
 Usage: php caligrafer.php test make <Name>   (writes tests/<Name>Test.php)
```
```bash
php caligrafer.php test make Books   # tests/BooksTest.php written: php caligrafer.php test Books
php caligrafer.php test              # every test of tests/
php caligrafer.php test Books        # only the tests whose name matches
```
PHPUnit with `framework/testing/bootstrap.php` and `Caligrafy\Testing\TestCase`. Each test runs in a transaction that is rolled back; `DB_TEST_DATABASE` or `.env.testing` gives the tests a database of their own. With no test yet: `No tests yet: php caligrafer.php test make <Name> writes tests/<Name>Test.php`. Without PHPUnit (`composer install --no-dev`) it says so and exits with `1`. Learn more in [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App).
## Check and maintain

### <a name="doctor"></a>`doctor`
```text
doctor [--only openai,groq] [--json] [--env <file>]: read-only health check of the project and of the services configured in .env
```
```bash
php caligrafer.php doctor
php caligrafer.php doctor --only database          # project, database, openai, groq, agent, stripe, coinbase, watson, mail
php caligrafer.php doctor --env .env.production    # another environment file
php caligrafer.php doctor --json                   # for scripts
```
```text
Caligrafy doctor (read-only): Caligrafy Quill 2.25.0

 Database
  OK    Database: connected to mysql://mysql:3306/caligrafy (server 8.4.13)
  OK    Framework tables: tokens, audit log, job runs, jobs, cache and migrations installed
  OK    Migrations: 1 ran, none pending

 3 OK, 0 WARN, 0 FAIL, 0 SKIP
```
It checks PHP and its extensions, `vendor/`, `.env` and the keys, the legacy API key, the Claude Code plugin, `public/uploads`, the web app manifest, the design style, whether `application/` is up to date, the database, the framework tables and the migrations, and every service configured in `.env` (OpenAI, Groq and the other agent providers, Stripe, Coinbase, Watson, mail). Each line is `OK`, `WARN`, `FAIL` or `SKIP` (not configured), with `-> <fix>`. Secrets are never printed. It exits with `1` when a check fails, and an unknown `--only` name lists the valid ones. With Docker, run it in the container so that `mysql` resolves. Run it first whenever something does not work.

### <a name="design"></a>`design`
```text
 Usage: php caligrafer.php design <list [--json] | show <name> | use <name> | off | status>
  list    the styles of application/design, framework/design/local and framework/design/vendor/* (the first one wins on a name clash)
  show    the path, description and stylesheet of a style
  use     selects a style: DESIGN_STYLE=<name> in .env (then /caligrafy-quill:design in Claude Code writes its stylesheet)
  off     back to Caligrafy's own look: DESIGN_STYLE= (stylesheets are kept)
  status  the selected style
```
`list` prints `85 styles (* selected, + stylesheet written)`: 84 from VoltAgent/awesome-design-md (MIT) in `framework/design/vendor/` and `interstellar` in `framework/design/local/`, plus yours in `application/design/<name>/DESIGN.md`. `status` with no style: `OK  Caligrafy's own look (DESIGN_STYLE is empty)`. Pages load `public/css/designs/<name>.css` once it exists; `/caligrafy-quill:design` writes it. Learn more in [Design styles](https://github.com/caligrafy/caligrafy-quill/wiki/Design-Styles).

### <a name="update"></a>`update`
```text
update [<version>] [--check] [--yes] [--no-composer]: moves the project to another release of Caligrafy Quill (the latest by default) and applies everything: framework/, the release's other files (untouched ones replaced, changed ones kept with a .caligrafy-new), composer.json, .gitignore and new .env settings merged, then upgrade --apply; backups in backups/
```
```bash
php caligrafer.php update --check      # what it would change, nothing written
php caligrafer.php update              # to the latest release
php caligrafer.php update 2.21.6       # to one release
```
On the latest release: `Caligrafy Quill 2.25.0 is the latest: nothing to update. php caligrafer.php upgrade checks application/.` It downloads the project's release and the target from GitHub, then:

1. replaces `framework/` and `claude-plugin/` whole (keeping `framework/librairies/app/.env`);
2. compares every other file of the release (`caligrafer.php`, `.bin/`, `Dockerfile`, `docker-compose.yaml`, `index.php`, `public/css`, `public/js`...) with the project's release: a file you never changed is replaced, a missing one is added, a file you changed is kept with the new version next to it as `<file>.caligrafy-new`. Your documents (`README.md`...) are left alone; `application/`, `tests/`, `qa/`, `public/uploads/` and `composer.lock` are never touched here;
3. merges `composer.json` (packages, scripts and, 2.22.1+, `config.allow-plugins`, where the project kept the release's value) and runs `composer update` for the new or changed packages (`--no-composer`: prints the command), adds the new lines of `.gitignore` and the new settings of `.env` with their defaults;
4. runs `php caligrafer.php upgrade --apply` for `application/`, and refreshes Claude Code's copy of the plugin.

What it replaces is first copied to `backups/caligrafy-update-<from>-to-<to>-<time>/`. With uncommitted git changes it stops (commit first, or `--yes`). It refuses a lower version. Then merge each `.caligrafy-new` into your file, delete it, and run `doctor`; `/caligrafy-quill:update` does the merges with Claude. A project before 2.9.0 gets the command first:
```bash
curl -fsSL https://raw.githubusercontent.com/caligrafy/caligrafy-quill/master/framework/core/Updater.php -o framework/core/Updater.php
php -r "require 'framework/core/Updater.php'; exit((new Caligrafy\Updater('.'))->run());"
```

### <a name="upgrade"></a>`upgrade`
```text
upgrade [--apply] [--local] [--force <application/path>] [--keep <application/path>]: brings the project up to date (dry run by default). When a newer release of Caligrafy Quill is out, it moves the project to it like update; otherwise (or with --local) it compares application/ with the framework templates and updates the untouched files; also reports .env settings and Bootstrap 3 classes
```
```bash
php caligrafer.php upgrade                                      # dry run
php caligrafer.php upgrade --local                              # application/ against this release's templates only
php caligrafer.php upgrade --apply                              # replace the files you never changed
php caligrafer.php upgrade --force application/views/Auth/login.pug          # replace one file you changed
php caligrafer.php upgrade --apply --keep application/views/default/index.pug   # keep a template copy that is now yours
```
```text
 Caligrafy upgrade (dry run: nothing is changed, run 'php caligrafer.php upgrade --apply' to update)
 Templates: framework/settings/application (45 files) compared with application/ - manifest .caligrafy-manifest.json found

  routes      application/config/routing/web.php: your routes: never replaced
  identical  44 file(s)

 Nothing was changed.
```
Each template file is `missing`, `identical`, `outdated` (an untouched older copy: replaced by `--apply`, with a backup in `backups/caligrafy-upgrade-<time>/`), `customized` (kept, the new version written next to it as `.caligrafy-new`), `kept` (`--keep`, remembered in the manifest), `held` (not added, with the reason: the user capabilities when they would clash with the project, `AuthController` or `AdminController` when its routes do not need them; `--force` adds one) or `routes` (`web.php`, never replaced). It also reports, without changing them: client apps in `public/` that differ from their template, settings of `.env.example` missing from `.env` and obsolete ones, and Bootstrap 3 classes in views and apps. Learn more in [Security and upgrading](https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading#upgrading).

### <a name="plugin"></a>`plugin`
```text
plugin: gives this project's Claude Code plugin its own source name and says where Claude Code reads it
```
```bash
php caligrafer.php plugin
```
```text
 Plugin source: caligrafy-7df2, plugin caligrafy-quill@caligrafy-7df2
```
It renames the plugin source of `.claude-plugin/marketplace.json` and `.claude/settings.json` from the shared `caligrafy` to the project's own name, then, when the `claude` command is on this computer, registers the source (`claude plugin marketplace add`), installs the plugin for the project, and refreshes Claude Code's copy when the project's plugin is newer. In Docker, where there is no `claude`, it says to run it on your computer. Restart `claude` in the folder afterwards. Run it when a `/caligrafy-quill:...` command is unknown.
## Put it online

### <a name="deploy"></a>`deploy`
```text
deploy [--wait <seconds>]: prepares the database in production: framework tables, every new or changed application/models/<folder>/create_db.sql (never one that drops or deletes data twice), then the pending migrations
```
```bash
php caligrafer.php deploy --wait 120      # wait up to 2 minutes for the database (default 60)
```
```text
 Caligrafy deploy
 caligrafy-schedule {"version":1,"jobs":[]}
  OK    Settings: .env compiled to .env.php (read without parsing on every request)
  OK    Framework tables: tokens, audit log, job runs, jobs, cache, migrations, scripts
  OK    application/models/Auth/create_db.sql: run
  OK    application/models/Bookshelf/create_db.sql: run
  OK    application/models/Tasks/create_db.sql: run
  OK    Migrations: up to date
```
The `caligrafy-schedule` line is the list of scheduled jobs, for Caligrafy Cloud. A script that has not changed since its last run says `up to date`. The production `Dockerfile` runs it before Apache starts (a failure is printed, and the site starts anyway). It compiles `.env`, waits for the database, creates the framework tables, runs each `application/models/<folder>/create_db.sql` that is new or changed since its last run (recorded in `caligrafy_scripts`), then the pending [migrations](#migrate). A changed script that drops, deletes or truncates is not run again (run it with [`sql`](#sql) when you mean it). Without `DB_ACTIVATE=true` it skips the database. It exits with `1` when the database cannot be prepared. Learn more in [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online#deploy).

### <a name="cloud"></a>`cloud`
```text
 Caligrafy Cloud: put this project online at https://<name>.caligrafy.com (https://deploy.caligrafy.com)
  cloud login [--no-browser]            sign in: approve the code in your browser (--token cq_... or --paste: a dashboard token)
  cloud account                         your email and credits
  cloud create <name> [--repo <url>] [--branch <b>]   from this project's GitHub repository
  cloud key <name>                      the read-only deploy key of a private repository (gh repo deploy-key add)
  cloud deploy <name> [--no-wait]       build and start it (every new app: 30 free minutes from its first deploy)
  cloud apps | status <name> | logs <name> [--jobs]
  cloud jobs <name> [run <job> | history <job>]   its scheduled jobs: last and next runs, run one now, its runs
  cloud extend <name> week|month|year   2, 5 or 50 credits
  cloud credits 5|10|25|50              buy credits (1 credit = 1 USD) on Stripe
  cloud submit <name> [--no-deploy]     send the marketplace listing (.caligrafy/marketplace.json), then deploy
  cloud secret set <name> KEY=value | secret list <name> | secret delete <name> KEY
  cloud delete <name> --yes             the app, its database and files, for good
  cloud logout
```
`php caligrafer.php cloud` (or `cloud help`) prints this list. Each app is built from its GitHub repository with its `Dockerfile`, with its own MySQL database, at `https://<name>.caligrafy.com`.
+ `login` prints a code and an address; open it, approve the code, and the token is saved in `.caligrafy/cloud.json` (ignored by git). In Docker it does not open the browser itself. `CALIGRAFY_CLOUD_TOKEN` and `CALIGRAFY_CLOUD_URL` override the file.
+ `create` takes the repository from the project's `origin` remote when `--repo` is missing (also in the Docker `dev-box`, which has no `git`: it reads `.git/config`), and says so when there is none. For a private repository it saves the read-only deploy key in `.caligrafy/<name>-deploy-key.pub`.
+ `deploy` follows the build (up to 15 minutes) unless `--no-wait`.
+ `secret set` adds a setting to the app's `.env`, applied at the next deploy.
+ `submit` sends the listing the `/caligrafy-quill:marketplace` skill wrote, then deploys.

Learn more in [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online#cloud).

### <a name="keys"></a>`generatekeys`, `generateapikey`
```text
generatekeys: generates an APP and an API pair of keys that you can put in your app's environment variable 
generateapikey: generates an API key that you can provide to any third party desiring to access your services
```
```bash
php caligrafer.php generatekeys       #  APP_KEY=...  API_KEY=...
php caligrafer.php generateapikey     #  API_KEY=... for the APP_KEY of .env
```
They print keys and write nothing. `initialize` already writes the keys: use `generatekeys` for another environment, or to replace a leaked `APP_KEY` (it signs everyone out). Legacy API keys are all the same key and cannot be revoked one by one: for programs and agents, use [`token`](#token).
## Related pages

+ [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart)
+ [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability)
+ [Getting Started](https://github.com/caligrafy/caligrafy-quill/wiki/1.-Getting-Started)
+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)
+ [Claude Code plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer-Project-Commands -->

The **project commands** of [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer) set a project
up and run its development server: `quickstart`, `initialize`, `created`, `server`, the shell launcher `.bin/caligrafer`,
and `version`. This page says what each one does, step by step, and what it prints.
## With Claude

`/caligrafy-quill:idea` and the [Quickstart with Claude](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart-with-Claude)
run `quickstart` for you; `/caligrafy-quill:server` starts, stops or checks the Docker server, and looks for a port
another project already holds before it starts it.

```text
/caligrafy-quill:server start
```

**Check** before you say OK: the address it prints opens the home page, and `php caligrafer.php doctor` has no `FAIL`.
## By hand

In a fresh copy of the framework (`composer create-project caligrafy/caligrafy-quill bookshelf`, or a clone):

```bash
cd bookshelf
.bin/caligrafer quickstart --example
```

With Docker running, it installs the PHP libraries, starts the `dev-box` container, and runs
`php caligrafer.php quickstart --example` in it. Then open `http://localhost:8080`. The whole walk-through, with its
output, is the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart).
## <a name="quickstart"></a>`quickstart`

```text
quickstart [--example] [--yes]: sets up a fresh project in one step (database, framework tables, /capabilities and /mcp); --example adds the Tasks example. With Docker: .bin/caligrafer quickstart
```

| Option | Effect |
| --- | --- |
| `--example` | adds the Tasks example: its capabilities, a model, a page, the `tasks` table, its routes and `public/js/capabilities.js` |
| `--yes` | allows the `initialize` step to delete the framework's `.git` |
| `--url <address>` | the address of the project on a local server, when it is not in a known web folder |
| `--no-db` | skips the database steps |
| `--db-defaults` | without a terminal, uses the local server's MySQL defaults instead of skipping the database |
| `--docker`, `--local` | `.bin/caligrafer` only: which server runs it (see [below](#bin)) |

Each step runs only when it is needed, so `quickstart` can be run again: it only does what is missing and never
overwrites a file.

1. `initialize`, when `application/` does not exist yet (refused without `--yes` when a `.git` folder is there).
2. The database settings: with Docker, `DB_ACTIVATE=true`, `DB_HOST=mysql` and `DB_DATABASE=caligrafy` in `.env`; on a
   local server (MAMP, XAMPP, LAMP), `APP_ROOT` from the project's place in the web folder and the MySQL settings,
   asked with the server's defaults.
3. The database itself (`CREATE DATABASE IF NOT EXISTS`) and the framework tables (`platform install`). A local MySQL
   that does not answer sets `DB_ACTIVATE=false` again.
4. `Route::capabilities('/capabilities')`, `Route::mcp('/mcp')` and `Route::notifications()` above `Route::run()` in
   `application/config/routing/web.php`.
5. With `--example`, the Tasks example.

The class behind it is [`Caligrafy\Quickstart`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#quickstart).
## <a name="initialize"></a>`initialize`

```text
initialize: Initializes and signs your project
```

```bash
php caligrafer.php initialize            # APP_ROOT=<folder name>: the site is at http://localhost/<folder>/
php caligrafer.php initialize off        # any word after initialize: APP_ROOT empty, the site is at the root (Docker)
php caligrafer.php initialize --yes      # also deletes .git without asking
```

```text
Preparing and signing the project for usage... 

 Contributor skill removed (.claude/skills/caligrafy-contributor: for the framework repository only)
 Claude Code plugin source: caligrafy-myapp-b6ea (enable caligrafy-quill@caligrafy-myapp-b6ea when Claude Code asks)
 .git kept (php caligrafer.php initialize --yes deletes it)
 Application initialized successfully
 APP_KEY=...
 API_KEY=...
```

What it does, in order:

1. **The keys.** It writes `APP_KEY` and `API_KEY` at the top of `.env`. A project that already has both keeps them
   (` Existing APP_KEY and API_KEY kept`): new keys would revoke the API keys, sign everyone out and make encrypted
   data unreadable.
2. **`APP_ROOT`.** Always rewritten: the folder's name, or empty when a word follows `initialize` (`.bin/caligrafer`
   adds `off` when no local Apache runs, because Docker serves the project at the root).
3. **The Vue SPA template.** It writes `framework/librairies/app/.env` with `VITE_API_ROUTE=` and no key: that build
   is public.
4. **`application/`.** When it does not exist, it copies `framework/settings/application` there and writes
   `application/.caligrafy-manifest.json`, which [`upgrade`](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer-Maintenance-Commands#upgrade)
   reads to tell your files from untouched copies. A failed copy prints
   ` Initialization failed: framework/settings/application could not be copied to ./application.` and exits with `1`.
5. **Uploads.** `public/uploads` is made writable (`chmod -R 777`).
6. **The contributor skill.** `.claude/skills/caligrafy-contributor` is for the framework's own repository: it is
   removed.
7. **The Claude Code plugin.** The project's plugin source gets its own name (`caligrafy-<folder>-<4 hex>`), so that
   Claude Code does not give every project the first one's plugin.
8. **`.git`.** Deleted only with `--yes`, or a `y` typed at the question in a terminal:
   ` This folder has a .git folder (the framework's history, or your project's). Delete it so that your project starts its own history? [y/N]`.
   Without a terminal (a script, Claude) and without `--yes`, it is kept.

> **Ask before `initialize --yes` in a git repository.** It deletes `.git`, and the history with it, unless it was
> pushed somewhere.
## <a name="created"></a>`created`

Composer runs it at the end of `composer create-project caligrafy/caligrafy-quill <folder>`; you never run it yourself.
It prints the folder, the one next command, and what it found on this computer:

```text
 Caligrafy Quill 2.25.0 is in /Users/me/www/bookshelf. One more command sets it up:

   cd bookshelf
   .bin/caligrafer quickstart --example
```

On Windows the command is `php caligrafer.php quickstart --example`. It then says the address when the folder is in the
web folder of a MAMP, XAMPP or LAMP server, that a running local server cannot see a folder outside its web folder, and
whether Docker is running (`quickstart uses it`, or `add --docker to use it instead`).
## <a name="server"></a>`server`

```text
server <start | stop | rebuild>: Starts a Caligrafy local LAMP server with phpmyadmin (requires PHP, Composer and Docker); rebuild updates the server image
```

| Command | Runs |
| --- | --- |
| `server start` | `docker compose up -d dev-box scheduler` |
| `server stop` | `docker compose stop` |
| `server rebuild` | `docker compose build --pull dev-box`, then `docker compose up -d dev-box scheduler` |

```text
Caligrafy Server successfully started.

 Hostname: http://localhost:8080
 phpmyadmin: http://localhost:8077
 mysql: localhost:3306 (from your computer; mysql:3306 from the containers)
 mysql username: root 
 mysql password: root 
```

+ **The containers** (`docker-compose.yaml`): `dev-box` (the PHP image of `docker/Dockerfile`, your folder mounted at
  `/var/www/html`), `scheduler` (the same image, running `php caligrafer.php schedule work`), `mysql` (MySQL 8.4) and
  `phpmyadmin` (5.2.3).
+ **The ports** it prints are the ones Docker published, so a `docker-compose.override.yml` that moves them (another
  project holds 8080) is followed; when the containers are not running, it reads the compose files and their override
  (2.24.0).
+ **The first start** builds the image and takes minutes; later starts take seconds. Run `rebuild` after a change to
  `docker/Dockerfile`, or to update the system packages.
+ **A local Apache.** Through `.bin/caligrafer`, `server` gets a last word: `local` when a local web server (MAMP,
  XAMPP, LAMP) runs, and then it only says that this server serves the project (turn it off to use Docker). Run by hand,
  `php caligrafer.php server start` always uses Docker (2.24.0).
+ **When it fails**: ` The Docker server could not start: is Docker Desktop running? (or a port is taken: docker-compose.override.yml moves them)`,
  exit code `1`.
## <a name="bin"></a>`.bin/caligrafer`

The shell launcher, for macOS and Linux:

```bash
.bin/caligrafer quickstart [--docker | --local] [quickstart options]
.bin/caligrafer <command> [options]
```

+ **`quickstart`** chooses the server: `--docker` or `--local`, else the local server when Apache (`httpd` or
  `apache2`) runs and PHP is installed, else Docker when it runs; with neither it says what to start. In a folder with a
  `.git` and no `application/` it asks before going on (the `initialize` step deletes `.git`) and adds `--yes` when you
  say `y`. It installs the PHP libraries when `vendor/autoload.php` is missing (your Composer, else the `composer:2`
  image with Docker), starts `dev-box` and runs `php caligrafer.php quickstart` in it, or runs it with your PHP. Then it
  registers the project's Claude Code plugin when the `claude` command is installed.
+ **Any other command**, with PHP and Composer on the computer: it runs `./caligrafer.php <command>` with your
  arguments as typed. `initialize` and `server` get the word that says whether a local server runs. A folder without
  `application/` or `.env` only accepts `initialize`, `version`, `doctor` and `update`, and otherwise prints
  ` This folder is not a Caligrafy project yet (no application/ or .env): start it with .bin/caligrafer quickstart`.
+ **Without PHP or Composer**, it runs `.bin/server start|stop`: the `prod-box` container, with the code copied into
  the image.
## <a name="version"></a>`version`

```bash
php caligrafer.php version        # also --version and -v
```

```text
Caligrafy Quill 2.25.0
```

It is handled before anything else is loaded: it works before `composer install` and never creates `.env`. In code, the
version is [`Caligrafy\Framework::VERSION`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#framework).
## Common mistakes

+ **`.git` gone after setting up** (G25, G95): `initialize` deletes it only with `--yes` or a typed `y` since 2.9.2;
  before, `.bin/caligrafer` ran `initialize` on its way to other commands and deleted it without asking.
+ **The ports clash with another project** (G12): `server start` fails. A `docker-compose.override.yml` remaps the host
  side (`"8081:80"`, `"8078:80"`, `"3307:3306"`), and `server` then prints the new ports.
+ **`.env` replaces the Docker settings** (G11): `.env` values win over the `environment` of `docker-compose.yaml`. Under
  Docker keep `DB_HOST=mysql` and `APP_ROOT=` (empty) in `.env`.
+ **`server start` does nothing** through `.bin/caligrafer` while a local Apache runs (G25): it serves the project
  itself. Stop it, or run `php caligrafer.php server start`.
## Related pages

+ [Caligrafer: every command](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer)
+ [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart) · [Quickstart with Claude](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart-with-Claude)
+ [Installation and configuration](https://github.com/caligrafy/caligrafy-quill/wiki/1.-Getting-Started)
+ [API reference: framework and tooling](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer-Build-Commands -->

The **build commands** of [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer) make features:
`service` writes a capability, `capabilities` lists them, `call` runs one from the terminal, `client` writes their
JavaScript client, and `app`, `create`, `facedetect`, `ml` and `bot` create client apps in `public/`.
## With Claude

```text
/caligrafy-quill:new-capability create_book books:write
/caligrafy-quill:new-app facedetect faces
```

`new-capability` runs `service`, fills the class, serves it, runs `client` and checks it with `call`;
`new-app` runs the app command and writes its routes.

**Check** before you say OK: `php caligrafer.php capabilities` lists the new capability with the scope you asked for,
and `php caligrafer.php call <name> ...` answers `{"data": ...}`.
## By hand

```bash
docker compose exec dev-box php caligrafer.php service Bookshelf/CreateBook --scope books:write
docker compose exec dev-box php caligrafer.php capabilities
docker compose exec dev-box php caligrafer.php call create_book title=Dawn published_year=1987 author_id=2
docker compose exec dev-box php caligrafer.php client
```

(without Docker, drop `docker compose exec dev-box`). [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability)
walks through the whole feature.
## <a name="service"></a>`service`

```text
 Usage: php caligrafer.php service <Name> [--scope <resource:action>] [--read-only]
 Name in PascalCase, optionally in folders: Books/CreateBook
```

```bash
php caligrafer.php service Bookshelf/CreateBook --scope books:write
php caligrafer.php service Bookshelf/ListBooks --scope books:read --read-only
```

```text
 Created application/services/Bookshelf/CreateBook.php: capability 'create_book' (scope books:write)
 Fill in $rules and handle(), then serve it: a page (Route::page data), a form (Route::form), REST (Route::capability or Route::capabilities), MCP (Route::mcp)
```

+ **The name** must be PascalCase, optionally in folders (`Books/CreateBook`). The capability is the snake_case of the
  class: `CreateBook` gives `create_book`.
+ **The file** is `application/services/<Name>.php`, written from `framework/settings/service.php.template`: a class
  that extends `Caligrafy\Service`, a `#[Capability(...)]` attribute with `name`, a placeholder `description`, `scope` and
  `readOnly`, empty `$rules`, `$filters` and `$descriptions`, and a `handle(array $input, Context $context)` that
  returns `array()`.
+ **`--scope`** fills `scope:`. Without it the capability needs no scope: anyone signed in, and any token, may call it.
+ **`--read-only`** sets `readOnly: true` (a page may read it; agents see it as safe).
+ It refuses an existing file (` <file> already exists`) and a project without `application/`
  (` application/ not found: run php caligrafer.php initialize first`), both with exit code `1`.
+ The other options of the attribute (`public`, `level`, `destructive`, `async`, `webOnly`) are added by hand.

What each part of the class means is in the API reference:
[`Caligrafy\Service`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#service) and
[`Caligrafy\Capability`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capability).
## <a name="capabilities"></a>`capabilities`

```text
capabilities [--json | --markdown]: the capabilities of application/services/ (what REST, MCP and the JS client can call)
```

```bash
php caligrafer.php capabilities              # one line each
php caligrafer.php capabilities --markdown   # a table for your documentation
php caligrafer.php capabilities --json       # with the input schemas
```

```text
 create_book                  books:write    writes    Adds a book to the Bookshelf catalog and returns it with its id and its author.
 get_book                     public         read      Returns one book of the catalog with its author (id, name, bio), by the id of the book.
```

| Column | What it says |
| --- | --- |
| 1 | the capability's name |
| 2 | who may call it: `public`, its scope, or `signed in` when it has no scope |
| 3 | `read` (`readOnly`), `destroys` (`destructive`) or `writes` |
| 4 | its description |

+ `--markdown` prints `| Capability | What it does | Scope | Inputs |`, with `(read-only)` or `(destructive)` after the
  name and `(required)` after each required input.
+ `--json` prints, for each one, `name`, `description`, `scope`, `level`, `readOnly`, `destructive`, `public` and
  `input`, its JSON Schema
  ([`Capabilities::describe()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#capabilities-describe)).
+ The framework's own capabilities (users, notifications, `queue_work`...) are listed too. Web-only capabilities are
  not: only `Route::action` reaches them.
+ With none: ` No capabilities yet: php caligrafer.php service <Name> creates one in application/services/`.
## <a name="call"></a>`call`

```text
 Usage: php caligrafer.php call <capability> ['{"key": "value"}' | key=value ...] [--token <token>] [--guest]
 Lists the capabilities: php caligrafer.php capabilities
```

```bash
php caligrafer.php call list_books
php caligrafer.php call get_book id=3
php caligrafer.php call create_book '{"title": "Dawn", "published_year": 1987, "author_id": 2}'
php caligrafer.php call create_book title=Dawn published_year=1987 author_id=2 --guest          # a visitor who is not signed in
php caligrafer.php call create_book title=Dawn published_year=1987 author_id=2 --token cq_...   # as a token
```

+ **Inputs**: one JSON object, `key=value` pairs, or both (merged in order). Anything else stops with
  `caligrafer call: '<arg>' is neither JSON nor key=value`. A `key=value` value is a string; the capability's rules
  check it as they check a form's values.
+ **Who calls**: without `--token` or `--guest`, the command line, with full access, like any script you run
  (`cli` in the audit log). `--guest` is a visitor: only public capabilities. `--token <token>`, or the
  `CALIGRAFY_TOKEN` environment variable, calls as that token, with its scopes; it needs the database, and a token that
  is unknown, revoked or expired stops with `caligrafer call: The token is unknown, revoked or expired`.
+ **The answer** is the JSON of REST, printed with indentation: `{"data": ...}` and exit code `0`, or
  `{"error": {"code": "invalid", "message": "...", "fields": {...}}}` and exit code `1`.
+ It never loads `application/config/config.php` (G141): a validator added there with `GUMP::add_validator()` does not
  exist on the command line.
## <a name="client"></a>`client`

```text
client [<file>] [--prefix /capabilities]: writes the JS client of the capabilities (default public/js/capabilities.js)
```

```bash
php caligrafer.php client                                   # public/js/capabilities.js
php caligrafer.php client public/myspa/src/capabilities.js  # a single page application
php caligrafer.php client --prefix /api/capabilities        # Route::capabilities('/api/capabilities')
```

```text
 public/js/capabilities.js written: 21 capabilities, calls /capabilities (Route::capabilities('/capabilities') in web.php)
 import { createBook, CapabilityError } from './capabilities.js'
```

+ One ES module with no dependency: one `export const` per capability (`create_book` becomes `createBook`), each with a
  doc comment made of the capability's description, its access and its inputs; plus `call(name, input)`,
  `capabilities()`, `configure({ baseUrl, token, prefix, credentials })` and `CapabilityError` (`status`, `code`,
  `fields`).
+ Web-only capabilities and Snap's own (`snap_*`) are left out.
+ `--prefix` must match the `Route::capabilities(...)` of `web.php`.
+ Run it again after every change to a capability.
+ ` Could not write <file>` and exit `1` when the folder cannot be written.

Learn more in [the JS client](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#client)
and [`Caligrafy\Client`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#client).
## <a name="apps"></a>`app`, `create`, `facedetect`, `ml`, `bot`

```text
create <project_name>: scaffolds a Vue project
app <project_name>: scaffolds a regular Client HTML/JS project
bot <bot_name>: creates a bot application
facedetect <app_name>: creates a face detection application
ml <app_name>: creates an ml powered application
```

| Command | Copies | Into | What it is |
| --- | --- | --- | --- |
| `app catalog` | `framework/plugins/app` | `public/catalog` | Vue 3 as a library |
| `create myspa` | `framework/librairies/app` | `public/myspa` | a Vite Vue single page application; `npm install` when `npm` is there |
| `facedetect faces` | `framework/plugins/facedetect` | `public/faces` | face detection and recognition |
| `ml lab` | `framework/plugins/ml` | `public/lab` | machine learning in the browser (ml5, p5) |
| `bot helper` | `framework/plugins/bot` | `public/helper` | a Watson chatbot |

```text
 Project created in the public folder.
 Type cd public/catalog to access it anytime
```

+ **The page route** of the app is not written by the command: add it to `web.php` (the
  [Vue pages](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.0-Setting-up-Vue.js-as-a-library) show it), or let
  `/caligrafy-quill:new-app` do it.
+ **Names that are refused**: `app`, `bot`, `__bots__`, `css`, `facedetect`, `fonts`, `images`, `js`, `ml`, `resources`,
  `uploads` (folders of `public/` the framework uses). A folder that exists already prints
  ` public/<name> already exists: nothing was created.` and exits with `1`.
+ **`create` and Node.js.** It runs `npm install` only where `npm` exists. The Docker `dev-box` has no Node.js, so there it
  prints ` VueJS project created, but its packages are NOT installed: npm is not available here (the Docker dev-box has no Node.js).`
  (G62): run `npm install`, then `npm run dev`, in `public/<name>` on your computer, with Node.js 20.19+ or 22.12+.
+ **A Vite app online** is served from its committed `dist/`: run `npm run build` and commit it, because the production
  image has no `npm`.

Learn more: [Vue as a library](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.0-Setting-up-Vue.js-as-a-library),
[the single page application](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.1---Setting-up-the-Vue-application),
[face detection](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition),
[machine learning](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.3-Machine-Learning),
[chatbots](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.1-Creating-Bots-with-Watson).
## Common mistakes

+ **A capability with no `--scope`**: any token can call it. Give every capability that changes data a scope.
+ **The client is out of date**: a capability added or changed after `client` ran is missing from
  `capabilities.js`, or called with old inputs. Run `client` again.
+ **A custom validator works on pages but not with `call`** (G141): `call`, the scheduler and the queue never load
  `config.php`. Register it where the command line loads it too, or use a built-in rule.
+ **`call ... | jq` hides a refusal** (G89): the pipe reports `jq`'s exit code. Use `set -o pipefail`, or read the
  `error` key.
## Related pages

+ [Caligrafer: every command](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer)
+ [Your first capability](https://github.com/caligrafy/caligrafy-quill/wiki/Your-First-Capability)
+ [Capabilities in depth](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP)
+ [API reference: services and capabilities](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer-Data-Commands -->

The **data commands** of [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer) work on the
database and the files the framework keeps for speed: `sql` runs a script, `migrate` runs and writes migrations,
`platform install` creates the framework tables, `cache clear` empties the cache, and `env` compiles `.env`.
## With Claude

```text
/caligrafy-quill:db add an isbn column to books
```

The `db` skill finds the database of `.env` (the Docker `mysql` container or a local MySQL), writes a migration with
`migrate make`, runs it, and shows the tables. It also runs `create_db.sql` scripts and fixes `[ERROR 2003]` and
"table doesn't exist" errors.

**Check** before you say OK: `php caligrafer.php migrate status` shows the new migration as `ran`, and
`php caligrafer.php doctor --only database` has no `FAIL`.
## By hand

A new project's tables, then a change to a table that holds data:

```bash
docker compose exec dev-box php caligrafer.php platform install
docker compose exec dev-box php caligrafer.php sql application/models/Bookshelf/create_db.sql
docker compose exec dev-box php caligrafer.php migrate make add_books_isbn
# write the ALTER TABLE in application/migrations/<YmdHis>_add_books_isbn.sql, then:
docker compose exec dev-box php caligrafer.php migrate
```

(without Docker, drop `docker compose exec dev-box`). Every command here reads the database of `.env`
(`DB_ACTIVATE=true` and the `DB_*` settings), or of another file with `--env <file>`.
## <a name="sql"></a>`sql`

```text
 Usage: php caligrafer.php sql <file.sql>
```

```bash
php caligrafer.php sql application/models/Bookshelf/create_db.sql
php caligrafer.php sql application/models/Bookshelf/create_db.sql --env .env.testing
```

```text
 application/models/Bookshelf/create_db.sql run on caligrafy
```

+ It removes the `/* ... */` comments and the lines that start with `--`, splits the rest on `;` and runs each statement.
+ A failure prints ` <file> could not be run: <reason>` and exits with `1`; the statements before it stay applied.
+ Without `DB_ACTIVATE=true`: `The database is not active: set DB_ACTIVATE=true and the DB_* settings in .env`.
+ Use it for the tables of a new database, and for a script the deploy step refused to run again because it drops or
  deletes data. A change to a table that holds data is a migration.
## <a name="migrate"></a>`migrate`

```text
 Usage: php caligrafer.php migrate [status | make <name>] [--env <file>]
 Runs the migrations of application/migrations that never ran on this database
```

```bash
php caligrafer.php migrate make add_books_isbn   # writes application/migrations/<YmdHis>_add_books_isbn.sql
php caligrafer.php migrate                       # runs the ones that never ran, in order
php caligrafer.php migrate status                # ran, pending or changed
php caligrafer.php migrate --env .env.testing    # on the database of another settings file (2.19.1)
```

**`make <name>`** needs no database. The name is lower-cased, and anything but letters and digits becomes `_`. The file
starts with two comment lines:

```sql
-- add_books_isbn
-- Runs once (php caligrafer.php migrate, and at every deploy). Never edit it after it ran: write a new one.
```

**`migrate`** runs, in number order, every file that never ran on this database, and records it in
`caligrafy_migrations` (its name, its sha256 and when):

```text
 OK   20261107232335_add_books_isbn.sql

 1 migration(s) run on caligrafy
```

With nothing to run: ` Nothing to migrate: caligrafy is up to date`. A file edited after it ran is not run again:
` WARN <file>: changed after it ran, not run again (write a new migration for the change)`.

**`status`** prints one line per file:

```text
 ran      20261107232335_add_books_isbn.sql  (2026-11-07 23:23:35)
 pending  20261108090000_add_loans_due_on.sql
```

| State | Means |
| --- | --- |
| `ran` | it ran on this database, and the file is what ran |
| `pending` | it never ran: the next `migrate` runs it |
| `changed` | it ran, and the file was edited since: it never runs again |

+ A file is named `<number>_<name>.sql` (up to 14 digits); any other `.sql` file in the folder stops the command with
  the name it expects. Two files with the same number stop it too.
+ The statements of a file are split on `;` outside quotes and comments. A file stops at its first failing statement,
  which the error names (`<file>, statement 2: ...`): it is not recorded, and what ran before it stays (MySQL commits a
  `CREATE` or `ALTER` at once). Keep one change per file, or write it so that it can run again.
+ Forward only: undo a change with a new migration.
+ `--env <file>` can come anywhere after `migrate`. Errors go to standard error, with exit code `1`.
+ The deploy step runs the pending ones at each start in production.

Learn more in [Migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations) and
[`Caligrafy\Migrations`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data#migrations).
## <a name="platform"></a>`platform install`

```text
 Usage: php caligrafer.php platform install
 Creates the framework tables (tokens, audit log, job runs, notifications, jobs, cache, migrations, Snap) from framework/settings/platform.sql
```

```text
 Framework tables ready: caligrafy_tokens, caligrafy_audit, caligrafy_job_runs, the notifications tables, caligrafy_jobs, caligrafy_cache, caligrafy_migrations and Snap's tables
```

It runs `framework/settings/platform.sql`, which creates each table only when it is missing: safe to run again, and
needed after an update that adds tables. `quickstart` and the deploy step run it. On failure:
` The framework tables could not be created: <reason>` and `Check DB_ACTIVATE and the DB_* settings in .env (php caligrafer.php doctor --only database)`,
exit code `1`.
## <a name="cache"></a>`cache clear`

```text
 Usage: php caligrafer.php cache clear
 Empties the cache (Caligrafy\Cache, CACHE_STORE in .env), the compiled views and the class map
```

```text
 Cache (database) emptied; 2 compiled view and class map file(s) removed
```

+ The cache of [`Caligrafy\Cache`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data#cache) in its store
  (`CACHE_STORE`: the `caligrafy_cache` table by default with `DB_ACTIVATE=true`, else private files). With the file
  store it says how many values it removed (`Cache (file) emptied: 3 value(s); ...`).
+ The compiled Pug views and the class map of this user, in the temporary folder.
+ Run it after copying files that keep their old modification times (`rsync -a`, `cp -p`): a view can look older than
  its compiled copy (G117).
+ The web server and the command line are different users: with `CACHE_STORE=file` each has its own folder, and the
  command line empties only its own (G119).

Learn more in [Caching](https://github.com/caligrafy/caligrafy-quill/wiki/Caching).
## <a name="env"></a>`env`

```text
 Usage: php caligrafer.php env <cache | clear>
```

```bash
php caligrafer.php env cache    # .env compiled to .env.php
php caligrafer.php env clear    # .env.php removed: pages read .env again
```

```text
 .env compiled to .env.php: pages read it without parsing .env (php caligrafer.php env clear removes it)
```

+ `.env.php` is a PHP array that `index.php` includes (OPcache keeps it) instead of parsing `.env` on every request.
  It holds the sha1 of the `.env` it was compiled from, and is used only while `.env` still has that content: edit
  `.env` and pages read it again at once.
+ It is written next to `.env` with the same permissions (and owner, when run as root), through a temporary file.
+ It holds the same secrets as `.env` and is in `.gitignore`: never commit it.
+ `env cache` with no `.env` prints ` env cache: no .env to compile, or .env.php could not be written` and exits with `1`.
+ The deploy step runs it at every start in production
  ([`Deployer::cacheEnv()`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#deployer-cacheenv)).
## Common mistakes

+ **Editing a migration after it ran** (G120): nothing happens, `status` says `changed` and `doctor` warns. Restore it
  and write a new one.
+ **A `;` inside a string of a `create_db.sql`**: `sql` and the deploy step split a script on every `;`, quotes
  included (migrations split outside quotes). Put such values in a migration, or avoid the `;`.
+ **`create_db.sql` that drops a table**: the deploy step runs a changed script again, but never one that drops or
  deletes (G68). Keep scripts safe to run twice (`CREATE TABLE IF NOT EXISTS`, added `ALTER TABLE ... ADD` lines).
+ **`migrate "" --env .env.testing`**: the empty word was needed before 2.19.1; write `migrate --env .env.testing`.
+ **A changed view still shows the old page after copying files** (G117): `cache clear`.
+ **`.env.php` in git**: it holds your secrets. The project's `.gitignore` leaves it out; keep it that way.
## Related pages

+ [Caligrafer: every command](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer)
+ [Migrations](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations) · [Caching](https://github.com/caligrafy/caligrafy-quill/wiki/Caching)
+ [The deploy step](https://github.com/caligrafy/caligrafy-quill/wiki/The-Deploy-Step)
+ [API reference: data](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer-Agent-Commands -->

The **agent commands** of [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer) are for programs
and AI agents that call your capabilities: `token` creates, lists and revokes personal access tokens, `mcp` serves the
capabilities to an agent on this computer, and `audit` shows what was called and refused.
## With Claude

```text
create a token for my reporting agent with books:read, valid 90 days
connect Claude Code to this app's capabilities
```

The `new-capability` skill runs `token create` (and shows the token once, without keeping it), and adds the app to
Claude Code with `claude mcp add ... php caligrafer.php mcp`.

**Check** before you say OK: `php caligrafer.php token list` shows the token `active` with only the scopes you asked
for, and `php caligrafer.php audit` shows the agent's calls.
## By hand

```bash
docker compose exec dev-box php caligrafer.php platform install        # the token and audit tables, once
docker compose exec dev-box php caligrafer.php token create "books agent" --scopes books:read,books:write
claude mcp add bookshelf -- docker compose exec -T dev-box php caligrafer.php mcp
docker compose exec dev-box php caligrafer.php audit --limit 20
```

(without Docker, drop `docker compose exec dev-box`, and `-T`).
## <a name="token"></a>`token`

```text
 Usage:
 php caligrafer.php token create <name> --scopes <a:read,b:write | *> [--user <id>] [--expires <days>]
 php caligrafer.php token list
 php caligrafer.php token revoke <id>
```

### `token create`

```bash
php caligrafer.php token create "books agent" --scopes books:read,books:write
php caligrafer.php token create "Reporting job" --scopes books:read --expires 90
php caligrafer.php token create "Sam's agent" --scopes "books:*" --user 7
```

```text
 Token #2 "books agent" created with books:read books:write

 cq_2_...

 It is shown only now: store it as a secret (Authorization: Bearer <token>).
```

| Option | Effect |
| --- | --- |
| `--scopes` (required) | `resource:action` values, separated by commas or spaces; `books:*` for every action on books; `*` for everything. A value of another shape is left out; with none left: ` A token needs scopes: --scopes books:read,books:write (or * for everything)` |
| `--expires <days>` | the token stops working after that many days (at least 1); the line says `, expires <date>` |
| `--user <id>` | the token acts for that user, so a capability's `level` applies to them and `$context->user` is that user. A user that does not exist: ` There is no user #<id>: no token was created.` |

Only the token's SHA-256 hash is stored: the token itself is printed once. A program sends it as
`Authorization: Bearer cq_...`.

### `token list`

```text
 #2    active   books agent                    books:read books:write  last used 2026-11-07 23:17:49
 #3    expired  Reporting job                  books:read  user 7  never used
```

The number, the state (`active`, `expired` or `revoked`), the name, the scopes, the user it acts for, and when it was
last used. With none: ` No tokens yet: php caligrafer.php token create <name> --scopes <scopes>`.

### `token revoke`

```bash
php caligrafer.php token revoke 2
```

```text
 Token #2 revoked
```

It takes the number without `#`, and stops the token at once. A number with no active token:
` No active token #<id>`.

Every `token` command needs the database and the framework tables: without them,
` The token table does not exist yet: run php caligrafer.php platform install`. The class behind them is
[`Caligrafy\Tokens`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#tokens).
## <a name="mcp"></a>`mcp`

```text
mcp [--token <token>]: MCP server over stdio for local AI agents (Claude Code, Cursor...): php caligrafer.php mcp
```

```bash
claude mcp add myapp -- php caligrafer.php mcp                                  # your own PHP
claude mcp add myapp -- docker compose exec -T dev-box php caligrafer.php mcp   # Docker
CALIGRAFY_TOKEN=cq_... php caligrafer.php mcp                                   # only what the token allows
```

+ **The protocol.** One JSON-RPC message per line on standard input, one answer per line on standard output; empty
  lines are skipped, notifications get no answer. The messages are those of
  [`Caligrafy\Mcp\Server`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces#mcp-server): `initialize`,
  `ping`, `tools/list` and `tools/call`. PHP errors go to standard error, so they never break the stream.
+ **The tools** are the capabilities, with their input schemas and the hints agents read before acting
  (`readOnlyHint`, `destructiveHint`). A call goes through the same checks, validation and audit as every other
  channel (channel `mcp`).
+ **Without a token** it has full access, like any script you run, and says so on standard error:
  `caligrafer mcp: no token, full local access (set CALIGRAFY_TOKEN to limit it)`.
+ **With a token** (`--token <token>`, or `CALIGRAFY_TOKEN`) it sees and calls only what the token's scopes allow. It
  needs the database (`caligrafer mcp: A token needs the database: set DB_ACTIVATE=true`), and a token that is unknown,
  revoked or expired stops it with exit code `1`.
+ **Agents on another computer** reach the application over HTTP: `Route::mcp('/mcp')` and a token. See
  [AI agents: MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#mcp).
## <a name="audit"></a>`audit`

```text
audit [--limit 50] [--capability <name>]: the latest capability calls
```

```bash
php caligrafer.php audit
php caligrafer.php audit --capability create_book --limit 200
```

```text
 2026-11-07 23:17:49  rest  token  2            create_book                  ok
 2026-11-07 23:17:49  rest  guest  -            create_book                  unauthenticated  Sign in or send a personal access token
```

| Column | What it says |
| --- | --- |
| when | `occurred_at`, in the server's time zone |
| channel | `web`, `rest`, `mcp` or `cli` (scheduled and background jobs run on `cli`) |
| who | `user`, `token`, `key`, `cli`, `guest`, or the system that ran it (`schedule`, `queue`) |
| id | the user's or the token's id, the job's name for a system, `-` for nobody |
| capability | its name |
| outcome | `ok`, `invalid`, `unauthenticated`, `forbidden`, `not_found`, `conflict` or `error`, and a short detail |

Every call that changes data and every refusal is recorded; a successful read is not, and inputs never are. With no
rows: ` The audit log is empty (or php caligrafer.php platform install was not run)`. The class behind it is
[`Caligrafy\Audit`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Capabilities#audit).
## Common mistakes

+ **`token revoke #2`** (G77): `#2` is read as `0` and nothing is revoked (` No active token #0`). Write
  `token revoke 2`.
+ **Tokens for an app online** (G79): an app on Caligrafy Cloud or your own server has no shell for `token create`.
  Give the app a page where signed-in people create their own tokens (a capability that calls `Tokens::create()` and
  refuses token contexts).
+ **A wrong token is a visitor** (G140): REST treats an unknown, revoked or expired `Bearer` token as no token, so a
  public capability still answers `200` (MCP over HTTP answers `401`). Check with `token list` that it is `active`.
+ **A token without `--user` passes any `level`** (G140): the level is a check on people. Keep the scopes of
  administrator capabilities off application tokens, or check the person in `handle()`.
+ **`mcp` with full access for an agent you do not control**: give it `CALIGRAFY_TOKEN` with the scopes it needs.
+ **A scope with a typo**: `--scopes book:read` creates a token for `book:read`, which no `books:read` capability
  accepts. Read the scopes `token create` prints.
## Related pages

+ [Caligrafer: every command](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer)
+ [Personal access tokens](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#tokens) · [the audit log](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#audit)
+ [Sign-in, users and tokens](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication#agents)
+ [API reference: interfaces](https://github.com/caligrafy/caligrafy-quill/wiki/API-Interfaces)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer-Job-Commands -->

The **job commands** of [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer) run work outside
a page: `schedule` runs capabilities on a timer, `queue` runs the background jobs your capabilities pushed, `notify`
sets up web push and sends a test, and `test` runs the app's tests.
## With Claude

```text
/caligrafy-quill:new-capability check_prices prices:write: run it every hour
/caligrafy-quill:new-capability send_welcome_email users:write: run it in the background after sign-up
```

The `new-capability` skill writes the job in `application/config/schedule.php` (or the `Queue::push(...)` call), runs
`schedule list` or `queue work --once` to check it, and writes its test.

**Check** before you say OK: `php caligrafer.php schedule list` lists the job with the rhythm you asked for, and
`php caligrafer.php test` ends with `OK (...)`.
## By hand

```bash
docker compose exec dev-box php caligrafer.php schedule list
docker compose exec dev-box php caligrafer.php schedule run check-prices
docker compose exec dev-box php caligrafer.php queue work --once
docker compose exec dev-box php caligrafer.php test
```

(without Docker, drop `docker compose exec dev-box`). The Docker server's `scheduler` container already runs
`schedule work` while it is up.
## <a name="schedule"></a>`schedule`

```text
 Usage: php caligrafer.php schedule <list [--json] | run <job> | due | work | history [<job>] [--limit 50]>
 Jobs are declared in application/config/schedule.php
```

| Command | What it does |
| --- | --- |
| `schedule list` | checks `schedule.php` (every job, its capability, its rhythm) and lists the jobs |
| `schedule list --json` | the same as one line of JSON (version 1): what Caligrafy Cloud reads at each deploy |
| `schedule run <job>` | runs one job now; `--if-due`: only when it is due this minute |
| `schedule due` | runs the jobs due this minute (for a cron line every minute) |
| `schedule work` | runs `due` every minute until stopped: ` Running the scheduled jobs every minute (Ctrl-C to stop)` |
| `schedule history [<job>] [--limit 50]` | the latest runs: when, the job, the outcome and its detail |

```text
 check-prices             every 1h       check_prices             UTC, timeout 55s
 nightly-report           0 2 * * *      build_report             Europe/Paris, timeout 120s (disabled)
```

+ A job calls one capability with fixed inputs, `every` one of `1m`, `5m`, `10m`, `15m`, `30m`, `1h`, `6h`, `12h`,
  `1d` (in UTC) or a five-field `cron` in its `timezone`, with a `timeout` (55 seconds by default, 300 at most).
+ One run at a time per job: a run that starts while the last one is still going is ` <job>: skipped, the previous run is still running`.
+ Each run is a child process stopped at its timeout, with full access like the command line, recorded in
  `caligrafy_job_runs` (kept 30 days).
+ Exit codes: `0` ok, `1` a job failed or timed out, `2` the file is invalid (every problem is printed, one per line),
  `3` skipped.
+ With no `schedule.php`: ` No scheduled jobs (application/config/schedule.php declares them)`.

Learn more in [Scheduled jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs) and
[`Caligrafy\Scheduler`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Jobs#scheduler).
## <a name="queue"></a>`queue`

```text
 Usage: php caligrafer.php queue <work [--queue default] [--for <seconds>] [--once] [--sleep 3] | status | list [--status failed] [--limit 50] | failed | retry <id | all>>
 Background jobs pushed with Caligrafy\Queue::push('<capability>', [...])
```

```bash
php caligrafer.php queue work --once      # what is due, then stops
php caligrafer.php queue work --for 300   # for 5 minutes
php caligrafer.php queue work             # until Ctrl+C
php caligrafer.php queue status
php caligrafer.php queue list --status failed
php caligrafer.php queue retry 42         # retry all: every failed job
```

```text
 Working the queue default until it is empty
 #12 send_welcome_email: done
 1 done, 0 to try again, 0 failed
```

| Command | What it does |
| --- | --- |
| `queue work` | runs the jobs of a queue (`--queue`, `default` by default): `--once` until it is empty, `--for <seconds>` for a while, else until stopped; `--sleep` is the pause when there is nothing to do (3 seconds) |
| `queue status` | ` 0 pending, 0 running, 0 done, 0 failed` |
| `queue list [--status <s>] [--limit 50]` | one line per job: its id, queue, capability, status, attempts, and when it may run or when it finished, with its last error |
| `queue failed` | `queue list --status failed` |
| `queue retry <id \| all>` | puts a failed job, or all of them, back in the queue: ` 1 failed job(s) back in the queue` |

+ Each job runs in its own process (`queue exec <id>`, internal), stopped at its timeout, with full access (G121): the
  capability that pushes the work checks who may ask for it.
+ A failed run is tried again after 30 s, 1 min, 2 min... until its attempts are used (3 by default); an input the
  capability refuses (invalid, not found) fails at once. Jobs are kept 7 days after they finish.
+ Online, a scheduled job on the framework's `queue_work` capability runs them every minute (Caligrafy Cloud runs it
  too), or a container of its own runs `queue work` for longer jobs.

Learn more in [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs) and
[`Caligrafy\Queue`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Jobs#queue).
## <a name="notify"></a>`notify`

```text
 Usage: php caligrafer.php notify <keys [--subject mailto:you@example.com] | test <user id> | status <user id>>
```

```bash
php caligrafer.php notify keys --subject mailto:you@example.com   # the web push keys, once
php caligrafer.php notify test 7                                  # a test notification to user 7
php caligrafer.php notify status 7                                # user 7's channels
```

+ **`keys`** writes `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` and `VAPID_SUBJECT` to `.env`:
  ` Web push keys written to .env (VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY, VAPID_SUBJECT=mailto:you@example.com). Keep them: new keys cut off every subscribed browser`.
  It refuses to replace keys that are there (exit `1`). The subject is a `mailto:` address or an `https://` address;
  without `--subject` it uses `MAIL_FROM` or `MAIL_USERNAME` when it is an email address, else `APP_URL`.
+ **`test <user id>`** sends ` Notifications work` (` A test from php caligrafer.php notify test.`) to the user's
  channels, and prints the result as JSON.
+ **`status <user id>`** prints, as JSON, the channels offered, then `push` (`configured`, `public_key`, the number of
  `browsers`, `enabled`) and `email` (`configured`, `address`, `confirmed`, `enabled`) for that user.

Learn more in [Notifications](https://github.com/caligrafy/caligrafy-quill/wiki/Notifications) and
[`Caligrafy\Notify`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Notify).
## <a name="test"></a>`test`

```text
 Usage: php caligrafer.php test make <Name>   (writes tests/<Name>Test.php)
```

```bash
php caligrafer.php test make Books   # writes tests/BooksTest.php
php caligrafer.php test              # every tests/*Test.php and tests/*/*Test.php
php caligrafer.php test Books        # only the tests whose class or method name matches
```

```text
 tests/BooksTest.php written: php caligrafer.php test Books
```

+ **`make <Name>`** writes a class that extends `Caligrafy\Testing\TestCase` with one test and commented examples of
  `$this->call(...)` and `$this->assertCapabilityFails(...)`. A trailing `Test` in the name is dropped; an existing file
  is refused. It also writes `tests/.gitignore` when the folder had none, or one that ignored every file (projects made
  before 2.18.0).
+ **`test [<filter>]`** runs PHPUnit with `framework/testing/bootstrap.php`, no configuration file,
  `--display-warnings` and `--fail-on-warning`: a warning fails the run. Its exit code is PHPUnit's.
+ With no tests: ` No tests yet: php caligrafer.php test make <Name> writes tests/<Name>Test.php` (exit `0`). Without
  PHPUnit (`composer install --no-dev`): ` PHPUnit is not installed: composer install (with the development packages), then php caligrafer.php test`
  (exit `1`).

How to write the tests: [Testing capabilities](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Capabilities),
[Testing pages, forms and actions](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Pages-Forms-and-Actions)
and [The test database](https://github.com/caligrafy/caligrafy-quill/wiki/The-Test-Database).
## Common mistakes

+ **A scheduled job expects someone signed in** (G108): a job runs with nobody signed in, as the system. Give it the
  ids it works on in its inputs.
+ **A background job trusts its input** (G121): it runs with full access. Check who may ask in the capability that
  pushes it.
+ **`skipped` read as a failure** (G150): it is a run that started while the same job was still going.
+ **New web push keys**: every browser that turned push on stops receiving. `notify keys` refuses to replace them;
  keep them across deploys.
+ **A test that creates a table** (G121): MySQL commits the `CREATE` and ends the test's transaction, so its rows stay.
## Related pages

+ [Caligrafer: every command](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer)
+ [Scheduled jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Scheduled-Jobs) · [Background jobs](https://github.com/caligrafy/caligrafy-quill/wiki/Background-Jobs) · [Notifications](https://github.com/caligrafy/caligrafy-quill/wiki/Notifications)
+ [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App)
+ [API reference: jobs, notifications and mail](https://github.com/caligrafy/caligrafy-quill/wiki/API-Jobs)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer-Maintenance-Commands -->

The **maintenance commands** of [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer) check and
keep a project current: `doctor` checks it, `design` picks its look, `update` and `upgrade` move it to a new release,
`plugin` connects its Claude Code plugin, and `snap` says what Snap Cards and the assistant need.
## With Claude

| You want | Ask |
| --- | --- |
| the latest release, with your changes merged | `/caligrafy-quill:update` |
| another look for every page | `/caligrafy-quill:design linear.app` |
| card views for the assistant | `/caligrafy-quill:assistant` |
| to know what is wrong | "run doctor and fix what fails" |

**Check** before you say OK: `php caligrafer.php doctor` has no `FAIL`, and after an update no `.caligrafy-new` file is
left.
## By hand

```bash
docker compose exec dev-box php caligrafer.php doctor
docker compose exec dev-box php caligrafer.php update --check
docker compose exec dev-box php caligrafer.php design list
```

(without Docker, drop `docker compose exec dev-box`). Run `doctor` first whenever something does not work.
## <a name="doctor"></a>`doctor`

```text
doctor [--only openai,groq] [--json] [--env <file>]: read-only health check of the project and of the services configured in .env
```

```bash
php caligrafer.php doctor
php caligrafer.php doctor --only database,mail
php caligrafer.php doctor --env .env.production
php caligrafer.php doctor --json
```

```text
Caligrafy doctor (read-only): Caligrafy Quill 2.25.0

 Database
  OK    Database: connected to mysql://mysql:3306/caligrafy (server 8.4.13)
  OK    Framework tables: tokens, audit log, job runs, jobs, cache and migrations installed
  OK    Migrations: 1 ran, none pending

 3 OK, 0 WARN, 0 FAIL, 0 SKIP
```

+ **The groups** (`--only`, separated by commas): `project`, `database`, `openai`, `groq`, `agent`, `stripe`,
  `coinbase`, `watson`, `mail`. An unknown name lists the valid ones.
+ **`project`** checks PHP (8.3 or later) and its extensions, `vendor/`, the keys (`APP_KEY`, `API_KEY`), `APP_DEBUG`,
  the legacy API key and the pages that still send it, the Claude Code plugin, `public/uploads`, the web app manifest and
  the service worker, the design style, forms without a method and Pug pitfalls in views, the schedule file,
  notifications, Snap's card views, changed framework files, and whether the templates of `application/` are up to
  date. **`database`** checks the connection, the framework tables, Snap's tables and the migrations. The others check each service configured in `.env`; a service that is not configured is
  `SKIP`.
+ **Each line** is `OK`, `WARN`, `FAIL` or `SKIP`, with `-> <fix>` under it when there is something to do.
+ **Read-only**: it lists, reads or connects, and never creates, charges or sends anything (Watson only opens and
  closes a session when its assistants cannot be listed). It never creates `.env`.
+ **Secrets** are never printed: at most a known prefix and the last 4 characters.
+ **Exit code** `1` when a check fails. `--json` prints the results for a script.
+ **With Docker**, run it in the container (`docker compose exec dev-box ...`) so that the host `mysql` resolves.

The class behind it is [`Caligrafy\Doctor`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#doctor).
## <a name="design"></a>`design`

```text
 Usage: php caligrafer.php design <list [--json] | show <name> | use <name> | off | status>
```

| Command | What it does |
| --- | --- |
| `design list` | the styles of `application/design`, `framework/design/local` and `framework/design/vendor/*` (the first wins on a name clash): ` 85 styles (* selected, + stylesheet written)` |
| `design list --json` | `{"selected": ..., "styles": [...]}` |
| `design show <name>` | its source, description, `DESIGN.md` and stylesheet, and the copies a clash hides |
| `design use <name>` | `DESIGN_STYLE=<name>` in `.env` |
| `design off` | `DESIGN_STYLE=` in `.env`: Caligrafy's own look; the stylesheets are kept |
| `design status` | the selected style, and whether its stylesheet exists |

`use` changes nothing on the pages until `public/css/designs/<name>.css` exists (G92):
` DESIGN_STYLE=<name> in .env. Its stylesheet public/css/designs/<name>.css is not written yet: pages keep Caligrafy's own look until it is.`
`/caligrafy-quill:design` writes it. Learn more in [Design styles](https://github.com/caligrafy/caligrafy-quill/wiki/Design-Styles).
## <a name="update"></a>`update`

```text
update [<version>] [--check] [--yes] [--no-composer]: moves the project to another release of Caligrafy Quill (the latest by default) and applies everything
```

| Option | Effect |
| --- | --- |
| `<version>` | a release (`2.21.6` or `v2.21.6`); the latest by default. A lower version than the project's is refused |
| `--check` | says what it would replace, add and keep, the new settings and packages; writes nothing |
| `--yes` | goes on although git has uncommitted changes |
| `--no-composer` | prints the `composer update` command instead of running it |

On the latest release: ` Caligrafy Quill 2.25.0 is the latest: nothing to update. php caligrafer.php upgrade checks application/.`
What it replaces, keeps and merges, and how to finish an update, is in
[Updating Caligrafy](https://github.com/caligrafy/caligrafy-quill/wiki/Updating-Caligrafy).
## <a name="upgrade"></a>`upgrade`

```text
upgrade [--apply] [--local] [--force <application/path>] [--keep <application/path>]: brings the project up to date (dry run by default)
```

| Option | Effect |
| --- | --- |
| (none) | a dry run: when a newer release is out, the same as `update --check`; else what it would change in `application/` |
| `--apply` | when a newer release is out, `update` to it; else replaces the files of `application/` you never changed |
| `--local` | compares `application/` with this release's templates only, without looking for a newer release |
| `--force <application/path>` | replaces one file you changed (a backup is kept) |
| `--keep <application/path>` | keeps an untouched template copy that is now yours (remembered in the manifest); can be given more than once |

Each template file is reported as `missing`, `identical`, `outdated`, `customized`, `kept`, `held` or `routes`. The
states, and what to do with each, are in [Updating Caligrafy](https://github.com/caligrafy/caligrafy-quill/wiki/Updating-Caligrafy#upgrade).
## <a name="plugin"></a>`plugin`

```text
plugin: gives this project's Claude Code plugin its own source name and says where Claude Code reads it
```

```text
 Plugin source: caligrafy-7df2, plugin caligrafy-quill@caligrafy-7df2
 Claude Code reads the plugin from /Users/me/www/bookshelf/claude-plugin: restart claude in this folder to load it
```

1. It renames the plugin source of `.claude-plugin/marketplace.json` and `.claude/settings.json` from the shared
   `caligrafy` to the project's own name (` (renamed from the shared "caligrafy")`). One name for every project gave
   them all the first one's plugin (G97).
2. When the `claude` command is on this computer, it registers the source (`claude plugin marketplace add`), installs
   `caligrafy-quill@<name>` for the project (`--scope project`), and, when Claude Code's copy of the plugin is older than
   the project's, refreshes it: ` Claude Code's copy of the plugin: <old>, now <new>`.
3. Without `claude` (in Docker) it says to run it on your computer.

A project with no `.claude-plugin/marketplace.json`: ` No .claude-plugin/marketplace.json: this project has no Claude Code plugin source (php caligrafer.php update brings it)`.
Run it when a `/caligrafy-quill:...` command is unknown, then restart `claude` in the folder. The class behind it is
[`Caligrafy\PluginSource`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#pluginsource).
## <a name="snap"></a>`snap`

```text
 Usage: php caligrafer.php snap [install | status | views]
```

```bash
php caligrafer.php snap install   # Snap's tables, and application/config/snap.php when there is none
php caligrafer.php snap           # what is ready (snap status)
php caligrafer.php snap views     # how each card that shows data looks (2.25.0)
```

```text
 Snap Cards and the assistant
  [ok] Tables            caligrafy_snap_*
  [ok] Route             Route::snap(); in application/config/routing/web.php
  [ok] Card hints        application/config/snap.php (optional: cards work without it)
  [--] Assistant model   ANTHROPIC_API_KEY in .env (without it the assistant answers from the cards' names)

 Then open /assistant (signed in), and /snap for every card.
```

`snap views` lists every read-only capability's card:

```text
 Card views (application/views/snap/<capability>.pug)
  [ok] get_book                   from Bookshelf/book.pug
  [!!] list_books                 Bookshelf/books.pug changed since its card view was made: write it again
  [--] get_user                   no card view: a card designed from its data
  [??] old_report                 no read-only capability of that name: the file is not used
```

It exits with `1` when a card view is stale. `install` and `status` need the database. Learn more in
[Snap Cards and the assistant](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant#looks),
[`Snap\Views`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-views) and
[`Snap\Setup`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Snap#snap-setup).
## Common mistakes

+ **`doctor | tail` says nothing failed** (G89): a pipe hides the exit code. Read the summary line, or use
  `set -o pipefail`.
+ **A new skill is missing after an update** (G103): Claude Code runs its own copy of the plugin. `php caligrafer.php plugin`
  on your computer refreshes it.
+ **`upgrade` says nothing changes on an old project** (G96): before 2.10.0 it never looked for a newer release. Run
  `update`.
+ **`design use` and the pages look the same** (G92): the style's stylesheet is not written yet.
## Related pages

+ [Caligrafer: every command](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer)
+ [Updating Caligrafy](https://github.com/caligrafy/caligrafy-quill/wiki/Updating-Caligrafy)
+ [Security and upgrading](https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading)
+ [Claude Code plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin)
+ [API reference: framework and tooling](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer-Deploy-Commands -->

The **deploy commands** of [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer) put a project
online: `deploy` prepares the database at each start in production, `cloud` runs the project on Caligrafy Cloud, and
`generatekeys` and `generateapikey` make keys for another environment.
## With Claude

```text
/caligrafy-quill:ship bookshelf
/caligrafy-quill:deploy --own-server
```

`ship` commits, creates the GitHub repository, pushes, signs in to Caligrafy Cloud with an approval in your browser,
runs `cloud create`, adds the deploy key, runs `cloud deploy` and checks the app online. `deploy --own-server` checks the
project and prepares it for your own server, and deploys nothing.

**Check** before you say OK: `php caligrafer.php cloud status bookshelf` says `running`, and
`https://bookshelf.caligrafy.com` opens.
## By hand

```bash
docker compose exec dev-box php caligrafer.php cloud login
docker compose exec dev-box php caligrafer.php cloud create bookshelf
docker compose exec dev-box php caligrafer.php cloud deploy bookshelf
```

(without Docker, drop `docker compose exec dev-box`). The whole walk-through is
[Deploying to Caligrafy Cloud](https://github.com/caligrafy/caligrafy-quill/wiki/Deploying-to-Caligrafy-Cloud).
## <a name="deploy"></a>`deploy`

```text
deploy [--wait <seconds>]: prepares the database in production: framework tables, every new or changed application/models/<folder>/create_db.sql (never one that drops or deletes data twice), then the pending migrations
```

```bash
php caligrafer.php deploy                 # what the production image runs at start
php caligrafer.php deploy --wait 120      # wait up to 2 minutes for the database (default 60)
```

```text
 Caligrafy deploy
 caligrafy-schedule {"version":1,"jobs":[]}
  OK    Settings: .env compiled to .env.php (read without parsing on every request)
  OK    Framework tables: tokens, audit log, job runs, jobs, cache, migrations, scripts
  OK    application/models/Bookshelf/create_db.sql: run
  OK    Migrations: up to date
```

The production image runs it before Apache starts. What it does, line by line, is
[The deploy step](https://github.com/caligrafy/caligrafy-quill/wiki/The-Deploy-Step). It exits with `1` when the
database could not be prepared, and `0` when it is ready or `DB_ACTIVATE` is not `true`.
## <a name="cloud"></a>`cloud`

`php caligrafer.php cloud` (or `cloud help`) prints the list. Every command calls a capability of Caligrafy Cloud
(`POST https://deploy.caligrafy.com/capabilities/<name>`) with the account's token, and exits with `1` when Cloud
refuses, with its message.

### Signing in

| Command | What it does |
| --- | --- |
| `cloud login` | prints a code and opens `https://deploy.caligrafy.com/cli?code=...` in your browser: approve the code there, and the command collects the token |
| `cloud login --no-browser` | the same without opening the browser: open the address it prints |
| `cloud login --token cq_...` | takes a token created on the dashboard |
| `cloud login --paste` | asks for that token at a prompt |
| `cloud account` | your email and credits |
| `cloud logout` | removes `.caligrafy/cloud.json` |

```text
 To sign in, approve this code in your browser: <code>
 https://deploy.caligrafy.com/cli?code=...
 Signed in as you@example.com (10 credits). The token is in .caligrafy/cloud.json (git-ignored).
```

The token is kept in `.caligrafy/cloud.json` (ignored by git, never in the image). `CALIGRAFY_CLOUD_TOKEN` gives one
instead, and `CALIGRAFY_CLOUD_URL` points to another service. In the Docker `dev-box` the browser does not open: open the
address it printed.

### Apps

| Command | What it does |
| --- | --- |
| `cloud create <name> [--repo <url>] [--branch <b>]` | the app, built from a GitHub repository: the project's `origin` remote when `--repo` is missing (read from `.git/config` in the `dev-box`, which has no `git`) |
| `cloud key <name>` | the read-only deploy key of an app built from a private repository, printed alone (for `> key.pub`) and saved in `.caligrafy/<name>-deploy-key.pub` |
| `cloud deploy <name> [--no-wait]` | builds and starts it, and follows the build up to 15 minutes unless `--no-wait` |
| `cloud apps` | your apps: name, status, address and time left |
| `cloud status <name>` | one app's status and time left, and `[password protected]` when it is locked |
| `cloud logs <name>` | the deploy step's lines, then what the app prints |
| `cloud logs <name> --jobs` | the latest runs of every scheduled job |
| `cloud jobs <name>` | its scheduled jobs, their last and next runs |
| `cloud jobs <name> run <job>` | runs one now (it starts within a minute) |
| `cloud jobs <name> history <job> [--limit 20]` | the runs of one job, with their output |
| `cloud delete <name> --yes` | the app, its database and files, for good; without `--yes` it only says what it would delete |

A private repository: `create` prints the deploy key and the command that adds it,
`gh repo deploy-key add .caligrafy/<name>-deploy-key.pub --title "Caligrafy Cloud"`. Add it before `cloud deploy`.
A failed build prints the last 30 lines of its log.

### Settings

| Command | What it does |
| --- | --- |
| `cloud secret set <name> KEY=value` | a setting of the app's `.env`, applied at the next deploy |
| `cloud secret list <name>` | the names of its settings (never their values) |
| `cloud secret delete <name> KEY` | removes one, applied at the next deploy |

The database settings, the keys, `APP_URL` and `LEGACY_API_KEY=false` are written for the app; your settings cannot
replace them.

### Time and credits

| Command | What it does |
| --- | --- |
| `cloud extend <name> week\|month\|year` | 2, 5 or 50 credits of time online, added to what is left; a paused app starts again |
| `cloud credits 5\|10\|25\|50` | prints the Stripe page that buys credits (1 credit = 1 USD) |

### The marketplace

| Command | What it does |
| --- | --- |
| `cloud submit <name> [--file .caligrafy/marketplace.json] [--no-deploy] [--no-wait]` | sends the listing the `/caligrafy-quill:marketplace` skill wrote, then deploys the app again for the screenshots of its key pages |

The class behind them is [`Caligrafy\CloudClient`](https://github.com/caligrafy/caligrafy-quill/wiki/API-Tooling#cloudclient).
## <a name="keys"></a>`generatekeys`, `generateapikey`

```text
generatekeys: generates an APP and an API pair of keys that you can put in your app's environment variable 
generateapikey: generates an API key that you can provide to any third party desiring to access your services
```

```bash
php caligrafer.php generatekeys       #  APP_KEY=...  API_KEY=...
php caligrafer.php generateapikey     #  API_KEY=... for the APP_KEY of .env
```

+ `generatekeys` makes a new `APP_KEY` (32 random bytes, base64) and the `API_KEY` encrypted from it. Use it for another
  environment (a production `.env`), or to replace a leaked `APP_KEY`: changing it signs everyone out and revokes every
  legacy API key.
+ `generateapikey` gives the `API_KEY` of the `APP_KEY` in `.env`. Legacy API keys are all the same key and cannot be
  revoked one by one: for programs and agents, use [`token`](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer-Agent-Commands#token).
+ Both print the keys and write nothing. `initialize` already writes the keys of a new project.
## Common mistakes

+ **`cloud deploy <name> | tail` looks fine** (G89): the pipe hides the exit code of a refused deploy. Run it whole.
+ **`deploy` answers *has no time left*** (G90): every new app is free for its first 30 minutes from its first deploy;
  then `cloud extend <name> week`.
+ **The build fails** (G69): `composer.lock` is missing or older than `composer.json`. Run `composer update` and commit
  the lock file.
+ **Pages get `[ERROR 1004]` online** (G87): Caligrafy Cloud turns the legacy API key off. Pages call their routes with
  the session (`apiHeaders()`, the JS client).
+ **A password-protected app answers a redirect** (G114): until it is offered to the marketplace, a locked app sends
  visitors to the unlock page and API calls get `401`.
## Related pages

+ [Caligrafer: every command](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer)
+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)
+ [Deploying to Caligrafy Cloud](https://github.com/caligrafy/caligrafy-quill/wiki/Deploying-to-Caligrafy-Cloud) · [your own server](https://github.com/caligrafy/caligrafy-quill/wiki/Deploying-to-Your-Own-Server)
+ [The deploy step](https://github.com/caligrafy/caligrafy-quill/wiki/The-Deploy-Step) · [the production image](https://github.com/caligrafy/caligrafy-quill/wiki/The-Production-Image)

<br/><br/>
>[Back to the documentation](https://github.com/caligrafy/caligrafy-quill/wiki)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/1.-Getting-Started -->

This page is the reference for installing Caligrafy Quill: what it needs, the recommended setup with Docker, the other setups (MAMP, XAMPP, LAMP, your own Apache), the address of a project (`APP_ROOT`), the server rules that protect your files, and the concepts and folders of a project. **New to Caligrafy?** Follow the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart): with Git and Docker, one command sets everything up.
## <a name="requirements"></a>Requirements

| | Needed |
| --- | --- |
| With Docker (recommended) | Git and Docker Desktop. PHP 8.5, Apache, MySQL 8.4 and phpMyAdmin 5.2.3 run in containers |
| On your own server | PHP 8.3 or higher (8.5 recommended) with `curl`, `json`, `mbstring`, `openssl` and `pdo_mysql` (and `gd`, `sodium`, `intl`, `zip`, `bcmath` for the features that use them); Apache with `mod_rewrite`, `mod_headers` and `mod_mime`, and `AllowOverride FileInfo` (or `All`); MySQL 8.4 (or another database PDO supports); Composer |
| For the Vue single page application template | Node.js 20.19+ or 22.12+ on your computer |

`php caligrafer.php doctor` checks the PHP version and extensions of a project.
## With Claude

Open the project folder in Claude Code and ask, or use the skill:
```text
/caligrafy-quill:server start
```
The `server` skill checks that Docker is running, that the ports 8080, 8077 and 3306 are free (it proposes other ports with a `docker-compose.override.yml` when one is taken) and that `.env` has the Docker settings (`DB_HOST=mysql`, an empty `APP_ROOT`), then starts the server and checks that the site answers. For a project from an idea, `/caligrafy-quill:idea` sets it up for you ([Quickstart with Claude](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart-with-Claude)).

**Check:** `http://localhost:8080` opens, and `docker compose exec dev-box php caligrafer.php doctor` ends with `0 FAIL`.
## Installation

### <a name="quickstart"></a><a name="using-docker"></a>With Docker (recommended)

```bash
git clone https://github.com/caligrafy/caligrafy-quill.git myapp
cd myapp
.bin/caligrafer quickstart --docker
```
Answer `y` when it asks to delete the framework's `.git`. Add `--example` for the Tasks example. The command installs the PHP libraries, builds and starts the Docker server, initializes the project, points `.env` at the Docker database, creates the database and the framework tables, and adds the `/capabilities` and `/mcp` routes. The full output and the troubleshooting are in the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart#start).

The Docker server (`docker-compose.yaml`):

| Service | Address | What it is |
| --- | --- | --- |
| `dev-box` | http://localhost:8080 | PHP 8.5 with Apache, your project folder mounted in it: a change to a file is live |
| `phpmyadmin` | http://localhost:8077 | phpMyAdmin, user `root`, password `root` |
| `mysql` | `127.0.0.1:3306` from your computer, `mysql:3306` from `dev-box` | MySQL 8.4, user `root`, password `root` |
| `scheduler` | | runs the scheduled jobs every minute (started by `server start`) |

Every day: `.bin/caligrafer server start` and `.bin/caligrafer server stop`. Run Caligrafer in the container: `docker compose exec dev-box php caligrafer.php <command>`. The first start builds the PHP image (it compiles the PHP extensions: from under a minute to about 5 minutes); later starts take seconds; `.bin/caligrafer server rebuild` builds it again after a change to `docker/Dockerfile`. Stop with `stop`, not `docker compose down`: the `mysql` container has no volume, and removing it removes the data.

**Without PHP on your computer**, `.bin/caligrafer server start` on a project that is not set up runs `.bin/server`: the `prod-box` container, with the code copied into the image and rebuilt when files change, at `http://localhost:8080/caligrafy-quill`. Use `quickstart --docker` instead: it serves your folder as it is.

### <a name="composer"></a>With Composer, on MAMP, XAMPP or LAMP

> #### ![](https://github.com/caligrafy/caligrafy-quill/blob/master/public/images/resources/play.png) [Installing Caligrafy](https://youtu.be/21Lazd38FfQ)
>
> A video of the installation on a local Apache, MySQL and PHP server.

In the web folder of your running local server (MAMP: the folder of its Apache settings, `htdocs` by default; XAMPP: `htdocs`; LAMP: `/var/www/html`):
```bash
composer create-project caligrafy/caligrafy-quill myapp
cd myapp
.bin/caligrafer quickstart --local
```
`composer create-project` installs the latest release (see the [changelog](https://github.com/caligrafy/caligrafy-quill/blob/master/CHANGELOG.md); `-s dev` takes the unreleased `master` branch) and prints the next command. `quickstart --local` gives the project its address (`APP_ROOT`, from its place in the web folder; MAMP's own settings are read), asks for the MySQL settings with the server's defaults, and creates the database, the framework tables and the routes. On Windows: `php caligrafer.php quickstart`. Details: [Quickstart, with Composer](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart#composer).

**Check:** open the address it prints, for example `http://localhost:8888/myapp` with a default MAMP.

### <a name="manual"></a>By hand, on your own Apache

1. Get the code in the web folder of your server (or in a folder a virtual host points to):
    ```bash
    git clone https://github.com/caligrafy/caligrafy-quill.git myapp
    cd myapp
    composer install
    ```
2. Initialize the project:
    ```bash
    php caligrafer.php initialize --yes
    ```
    ```text
     .git deleted: git init starts your project's own history
     Application initialized successfully
    ```
    It creates `.env` from `framework/settings/.env.example`, writes a new `APP_KEY` and `API_KEY`, sets `APP_ROOT=myapp` (the folder name), copies the templates to `application/` and makes `public/uploads` writable. For a site at the root of its address (a virtual host), run `php caligrafer.php initialize off --yes` instead: `APP_ROOT` is then empty.
3. Point `.env` at your database:
    ```text
    DB_ACTIVATE=true
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=myapp
    DB_USERNAME=root
    DB_PASSWORD=<your password>
    ```
    Use `127.0.0.1`, not `localhost`: with `localhost`, PDO uses the MySQL socket and ignores `DB_PORT`.
4. Create the database, the framework tables and the routes:
    ```bash
    php caligrafer.php quickstart --url http://localhost/myapp
    ```
    It finds the database settings already set, so it asks nothing, and ends with `Ready. Next:`.
5. Check:
    ```bash
    php caligrafer.php doctor
    ```
    and open `http://localhost/myapp` (your server's port and path).

`php caligrafer.php generatekeys` prints a new key pair when you need one for another environment.

### <a name="different-root-folder"></a>The project's address: `APP_ROOT`

`APP_ROOT` in `.env` is the path of the project under the address of the server, without slashes:

| The project is served at | `APP_ROOT` |
| --- | --- |
| `http://localhost:8080/` (Docker), or a virtual host | empty |
| `http://localhost/myapp/` | `myapp` |
| `http://localhost/clients/myapp/` | `clients/myapp` |

`initialize` sets it to the folder name (`initialize off`: empty), and `quickstart` sets it from the project's place in the web folder of MAMP, XAMPP or LAMP. Rename the folder, or move it, and change `APP_ROOT` to match.

### <a name="virtualhosts"></a>Virtual hosts

A virtual host is optional. It must allow the project's `.htaccess` files:
```text
<VirtualHost *:80>
    ServerName bookshelf.test
    DocumentRoot "/path/to/myapp"
    <Directory "/path/to/myapp">
       Options FollowSymLinks
       AllowOverride All
       Require all granted
    </Directory>
</VirtualHost>
```
Add `127.0.0.1 bookshelf.test` to `/etc/hosts`, restart Apache, and set `APP_ROOT=` (empty).
## <a name="protecting-your-server-files"></a>Protecting your server files

Only `index.php` and the `public` folder are meant to be reached from a browser. The `.htaccess` file at the root of the project answers `403` for existing:
+ dotfiles and dot folders, such as `.env`, `.env.php`, `.git` and `.claude` (`.well-known` stays reachable);
+ the folders `application`, `framework`, `vendor`, `tests`, `qa`, `docker`, `claude-plugin`, `archives`, `backups` (2.19.1) and `node_modules`;
+ the files `caligrafer.php`, `composer.json`, `composer.lock`, `docker-compose.yaml` (or `.yml`), `package.json` and `package-lock.json`, and any `.sql`, `.log`, `.bak`, `.ini`, `.sh` or `.env` file.

Every other address goes to `index.php?uri=<path>`, the front controller. A second `.htaccess` in `public/uploads` stops any script that ends up there from running or being downloaded. The rules are case-insensitive (macOS and Windows file systems).

Keep these files when you deploy. They need `mod_rewrite`, `mod_headers` (CORS, cookies, the service worker scope) and `mod_mime` (the web app manifest type), and `AllowOverride FileInfo` (or `All`): without `mod_headers`, Apache answers `500`. Check a server with `curl -I http://<your-host>/.env`: the answer must be `403` or `404`.

**nginx** ignores `.htaccess`. Use equivalent rules, for example:
```text
location ~ /\.(?!well-known) { deny all; }
location ~ ^/(application|framework|vendor|tests|qa|docker|claude-plugin|archives|node_modules|backups)/ { deny all; }
location ~ ^/(caligrafer\.php|composer\.(json|lock)|docker-compose\.ya?ml|package(-lock)?\.json)$ { deny all; }
location ~* \.(sql|log|bak|ini|sh|env)$ { deny all; }
location = /public/sw.js { add_header Service-Worker-Allowed "/"; }
types { application/manifest+json webmanifest; }
location ~* ^/public/uploads/.*\.(php\d*|phtml|phar|cgi|pl|py|sh)$ { deny all; }
location / { try_files $uri $uri/ /index.php?uri=$uri&$args; }
```

PHP's built-in server (`php -S`) reads no `.htaccess`: it neither routes the pages nor protects these files. Use Docker or Apache.
## <a name="caligrafer"></a>Caligrafer, the command line tool

`php caligrafer.php <command>` (with Docker: `docker compose exec dev-box php caligrafer.php <command>`). **Every command is on one page: [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer).** The ones you use most:

| Command | What it does |
| --- | --- |
| `quickstart [--example]` | sets a project up in one step ([details](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#quickstart)) |
| `service <Folder/Name> --scope <scope>` | creates a capability ([details](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#service)) |
| `call <capability> key=value` | calls a capability and prints its answer ([details](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#call)) |
| `sql <file.sql>` | runs a SQL script, such as a model's `create_db.sql` ([details](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#sql)) |
| `migrate [status \| make <name>] [--env <file>]` | changes tables that hold data ([details](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#migrate)) |
| `client` | writes the JavaScript client of the capabilities ([details](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#client)) |
| `token create <name> --scopes ...` | a token for a program or an AI agent ([details](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#token)) |
| `test [make <Name>]` | runs your app's tests, or writes one ([details](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#test)) |
| `doctor` | checks the project and its services ([details](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#doctor)) |
| `update` | moves the project to a newer release ([details](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#update)) |

+ <a name="version"></a>The version of a project: `php caligrafer.php version` prints `Caligrafy Quill 2.25.0` ([details](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#version)).
+ <a name="buildoncecommands"></a>Capabilities, tokens, MCP and the audit log: `service`, `capabilities`, `call`, `client`, `platform install`, `token`, `mcp`, `audit` ([details](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#service)).
+ <a name="doctor"></a>Something does not work: `php caligrafer.php doctor` checks the project, the database and every service of `.env`, with a fix for each problem ([details](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#doctor)).
## <a name="architecture"></a>How a project is built

Caligrafy is a Model-View-Controller framework with one more layer on top, so that a feature is **built once and experienced everywhere**:

| Layer | What it holds | Where |
| --- | --- | --- |
| **Capabilities** | the features, written once: inputs and their rules, who may use them, the work, the result | `application/services/` (a `Caligrafy\Service` with `#[Capability]`) |
| **Experiences** | every way to reach a capability | Pug pages (`Route::page`, `Route::form`, `Route::action`), Vue apps (the JavaScript client), REST (`Route::capability`, `Route::capabilities`), AI agents (`Route::mcp`) |
| **Models** | one class per table, read and written by capabilities only | `application/models/` |
| **Views** | the Pug pages | `application/views/` |
| **Controllers** | older code and the examples a new project ships; a new request never needs one | `application/controllers/` |

### <a name="buildonce"></a>Build once, experience everywhere

A capability is called the same way by every experience, so its rules never drift between the web pages, the apps, the API and the agents. [How Caligrafy works](https://github.com/caligrafy/caligrafy-quill/wiki/How-Caligrafy-Works) explains it in 5 minutes; [Build Once](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP) has every option.

### <a name="namespace"></a>The `Caligrafy` namespace

The framework's classes are in the namespace `Caligrafy`. Your classes are global (no namespace) unless you give them one, and `use` the framework classes they extend:
```php
<?php

use Caligrafy\Model;

class Book extends Model
{
    public $id;
    public $title;
}
```
Two classes of `application/` cannot have the same fully qualified name: name them distinctly (`Book`, `ListBooks`, `BookFormController`) or give them a namespace.
## <a name="fundamentals"></a>Fundamentals

The Bookshelf (books, authors, tags, loans) is the example of this wiki.

+ **Capabilities**: one feature of the application (list the books, add a book) written once as a class: it declares its inputs with [validation rules](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation), the scope and permission level it needs, does the work and returns data. Learn more [here](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#service).
+ **Routes**: the lines of `application/config/routing/web.php` that connect an address to what answers it. `Route::page('/books', 'Bookshelf/books', ['data' => ['books' => 'list_books']])` shows a page with the result of a capability; `Route::form('/books', 'create_book')` takes a form; `Route::capability('GET', '/api/books', 'list_books')` is a REST address. Learn more in [Routing](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing) and [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes).
+ **Experiences**: web pages, Vue apps and single page applications on any device, REST clients and AI agents (MCP) all call the same capabilities, each shaped for its audience.
+ **Identity**: people sign in (`Route::auth`, passkeys); programs and AI agents use personal access tokens with scopes, which can expire and be revoked. Every change and every refusal goes to the audit log.
+ **Models**: one class per table, with one public property per column. The [query builder](https://github.com/caligrafy/caligrafy-quill/wiki/Queries) of a model (`Book::where(...)`, `Book::insert(...)`) reads the table named after the class (`Book` -> `books`) unless the model declares `protected static $tableName`. Learn more in [Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models).
+ **Queries**: lists, filters, paging and related rows with every value bound: `Database::table('books')`, `Book::where('author_id', 3)->with('author')->paginate(20, $page)`.
+ **Relationships**: a book's author, an author's books, a book's tags through a pivot table: a capability loads them with `with()` (`Book::with('author')`), which reads them from the names of the tables and columns, with no code in the model. Learn more in [Relationships](https://github.com/caligrafy/caligrafy-quill/wiki/5.-Relationships).
+ **Naming conventions**:
    1. Every table's primary key is `id`.
    2. A foreign key is `<model name in lower case>_id` (`author_id` for the model `Author`), of the same type as the `id` it references (`INT UNSIGNED` for an `INT UNSIGNED` id), and every foreign key constraint has a name unique in the database (`fk_books_author_id`: `fk_<table>_<column>`).
    3. A many-to-many pivot table is `<table1>_<table2>` (`books_tags`, with `book_id` and `tag_id`), written in `create_db.sql` like any table; `with(['tags' => ['pivot' => true]])` on `books` reads `books_tags`, or `tags_books` when only that one exists.
+ **Tables**: a new table is a `create_db.sql` next to its model (`php caligrafer.php sql ...`); a change to a table that holds data is a [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations).
+ **Views**: Pug pages rendered on the server ([Views](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views)), or Vue apps in `public/` that call the capabilities through the JavaScript client.
+ **Validation**: the rules of [GUMP](https://github.com/Wixel/GUMP), in each capability's `$rules`.
## <a name="filestructure"></a>File structure

| Folder | What goes there |
| --- | --- |
| `application/` | your application: `services/` (capabilities), `models/`, `views/`, `controllers/`, `config/` (`routing/web.php`, `config.php`, and `schedule.php` or `container.php` when you add them), and `migrations/` once you write one. Each class is loaded the first time it is used, from a class map Caligrafy keeps up to date: no `require` |
| `framework/` | the framework. `core/` holds the framework classes (`Service`, `Capability`, `Context`, `Route`, `Model`...), `interfaces/` the REST, MCP and JavaScript client channels, `settings/` the templates `initialize` copies. Change it only to change the framework |
| `public/` | what the browser loads: scripts, stylesheets, images, client apps, and `public/uploads/` for uploaded files |
| `tests/` | your app's tests, run with `php caligrafer.php test` ([Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App)). Never loaded by a page; the production image leaves it out |
| `vendor/` | the libraries Composer installs |
## Related pages

+ [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart)
+ [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer)
+ [How Caligrafy works](https://github.com/caligrafy/caligrafy-quill/wiki/How-Caligrafy-Works)
+ [Security and upgrading](https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading)
+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)

<br/><br/>

> [Next Section: Learn about Routes](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing -->

# Routing

A route connects an address (`GET /books/3`) to what answers it. Every route of a Caligrafy project is one line of
`application/config/routing/web.php`. A route names a capability (a feature written once, in `application/services/`)
and says how the web reaches it: a page that shows its data (`Route::page`), a form that calls it (`Route::form`), a file
to download (`Route::download`), a JSON API (`Route::capability`), or anything else a browser asks (`Route::action`).
Since 2.21.0 every request can be declared this way, so a new application has no controller. This page covers how routes
match, pages, redirects and capability routes. Forms, sign-in, webhooks, downloads and `Route::action` have their own
page: [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes).

## With Claude

Ask for the feature, not the route: the `caligrafy-quill` plugin writes the capability and the routes together.

```text
/caligrafy-quill:new-resource Book title:string published_year:int author:fk
```

or, for one feature:

```text
/caligrafy-quill:new-capability get_book books:read read-only
"Show each book on its own page at /books/{id}, with a 'Book not found' page when the id does not exist."
```

What Claude writes: the capabilities in `application/services/<Folder>/`, the routes in
`application/config/routing/web.php` (`Route::page` for pages, `Route::form` for forms, `Route::capability` for the
REST API, inside the `try` block and before `Route::run();`) and the Pug views in `application/views/`.

**Check** before you say OK:

- [ ] Every new route is in the `try` block of `web.php`, before `Route::run();`.
- [ ] Pages are `Route::page`, forms are `Route::form`, a custom request is `Route::action`: no controller and no closure
      that reads or writes data.
- [ ] A fixed address such as `/books/new` comes before `/books/{id}` (the first route that matches wins).
- [ ] Each page's `data` names a read-only capability (`readOnly: true`).
- [ ] `curl -i` of each new address answers the status you expect (200, 302, 404).

## <a name='definingroutes'></a>By hand

You need a project from the [Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart) with its
database. The commands below run in the project folder; with the Docker dev server, run them as
`docker compose exec dev-box php caligrafer.php ...`. The addresses use `http://localhost:8080`, the Docker dev server.

1. **Create the Bookshelf tables.** Write `application/models/Bookshelf/create_db.sql` (it can run more than once: it
   never drops anything):

   ```sql
   /* Bookshelf: the first version of its tables, and sample books.
    * Run it with: docker compose exec dev-box php caligrafer.php sql application/models/Bookshelf/create_db.sql
    * Safe to run again: CREATE TABLE IF NOT EXISTS skips a table that exists, INSERT IGNORE a row whose id exists.
    */

   CREATE TABLE IF NOT EXISTS authors (
       id INT UNSIGNED NOT NULL AUTO_INCREMENT,
       name VARCHAR(150) NOT NULL,
       bio TEXT NULL,
       created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
       modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
       PRIMARY KEY (id)
   ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;

   CREATE TABLE IF NOT EXISTS books (
       id INT UNSIGNED NOT NULL AUTO_INCREMENT,
       title VARCHAR(200) NOT NULL,
       published_year SMALLINT UNSIGNED NOT NULL,
       summary TEXT NULL,
       author_id INT UNSIGNED NOT NULL,
       created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
       modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
       PRIMARY KEY (id),
       KEY idx_books_author_id (author_id),
       CONSTRAINT fk_books_author_id FOREIGN KEY (author_id) REFERENCES authors (id)
           ON UPDATE CASCADE ON DELETE RESTRICT
   ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;

   -- Sample data, with fixed ids so that book 3 is Kindred everywhere
   INSERT IGNORE INTO authors (id, name, bio) VALUES
       (1, 'Ursula K. Le Guin', 'American author of science fiction and fantasy, known for the Earthsea books.'),
       (2, 'Octavia E. Butler', 'American science fiction author, the first to receive a MacArthur fellowship.'),
       (3, 'Italo Calvino', 'Italian writer of playful, inventive novels and short stories.');

   INSERT IGNORE INTO books (id, title, published_year, summary, author_id) VALUES
       (1, 'A Wizard of Earthsea', 1968, 'A gifted boy learns magic and must face the shadow he set loose.', 1),
       (2, 'The Left Hand of Darkness', 1969, 'An envoy visits a planet whose people have no fixed sex.', 1),
       (3, 'Kindred', 1979, 'A young woman is pulled back in time to a plantation in Maryland.', 2),
       (4, 'Parable of the Sower', 1993, 'In a collapsing California, a teenager starts a new belief system.', 2),
       (5, 'Invisible Cities', 1972, 'Marco Polo describes imaginary cities to the emperor Kublai Khan.', 3);
   ```

   Run `docker compose exec dev-box php caligrafer.php sql application/models/Bookshelf/create_db.sql`. It prints
   ` application/models/Bookshelf/create_db.sql run on caligrafy`. A later change to these tables, once they hold
   data, is a [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations).

2. **Describe an author and a book.** Write `application/models/Bookshelf/Author.php`:

   ```php
   <?php

   use Caligrafy\Model;

   // One Author = one row of the authors table (Author::query() reads authors: the class name in lower case, plus s)
   class Author extends Model {

       // one public property per column of the table
       public $id;
       public $name;
       public $bio;
       public $created_at;
       public $modified_at;
   }
   ```

   and `application/models/Bookshelf/Book.php`:

   ```php
   <?php

   use Caligrafy\Model;

   // One Book = one row of the books table. Book::with('author') adds the row of authors whose id is author_id
   class Book extends Model {

       // one public property per column of the table
       public $id;
       public $title;
       public $published_year;
       public $summary;
       public $author_id;
       public $created_at;
       public $modified_at;
   }
   ```

3. **Write the two capabilities the pages read.** Run:

   ```bash
   docker compose exec dev-box php caligrafer.php service Bookshelf/ListBooks --scope books:read --read-only
   docker compose exec dev-box php caligrafer.php service Bookshelf/GetBook --scope books:read --read-only
   ```

   Each prints ` Created application/services/Bookshelf/<Name>.php: capability '<name>' (scope books:read)`. Replace
   the content of `application/services/Bookshelf/ListBooks.php` with:

   ```php
   <?php

   use Caligrafy\Capability;
   use Caligrafy\Context;
   use Caligrafy\Service;

   // list_books: the catalog, sorted by title, 20 books per page, each with its author. Anyone may read it
   #[Capability(
       name: 'list_books',
       description: 'Lists the books of the Bookshelf catalog, sorted by title, 20 per page, each with its author (id, name, bio). Give author_id to list only the books of one author, and page for the next pages. Returns data (the books), total, page, per_page and pages.',
       scope: 'books:read',
       readOnly: true,
       public: true
   )]
   class ListBooks extends Service
   {
       public $rules = array('author_id' => 'integer', 'page' => 'integer');
       public $descriptions = array(
           'author_id' => 'Optional: only the books of this author',
           'page' => 'Optional: the page, 1 by default (20 books per page)'
       );

       public function handle(array $input, Context $context)
       {
           // two queries for the page (the count, then the books) and one for all their authors
           $query = Book::with('author')->orderBy('title');
           if (!empty($input['author_id'])) {
               $query->where('author_id', $input['author_id']);   // the value is bound, never pasted into the SQL
           }
           return $query->paginate(20, $input['page'] ?? 1);
       }
   }
   ```

   and the content of `application/services/Bookshelf/GetBook.php` with:

   ```php
   <?php

   use Caligrafy\Capability;
   use Caligrafy\Context;
   use Caligrafy\Service;
   use Caligrafy\ServiceError;

   // get_book: one book with its author, or "not found"
   #[Capability(
       name: 'get_book',
       description: 'Returns one book of the catalog with its author (id, name, bio), by the id of the book.',
       scope: 'books:read',
       readOnly: true,
       public: true
   )]
   class GetBook extends Service
   {
       public $rules = array('id' => 'required|integer');
       public $descriptions = array('id' => 'The id of the book');

       public function handle(array $input, Context $context)
       {
           $book = Book::with('author')->find($input['id']);
           if (!$book) {
               throw ServiceError::notFound("There is no book #{$input['id']}");
           }
           return $book;
       }
   }
   ```

   Run `docker compose exec dev-box php caligrafer.php capabilities`: the list shows `get_book` and `list_books`, both
   `public` and `read`.

4. **Declare the routes.** In `application/config/routing/web.php`, inside the `try` block, after
   `Route::page('/', 'default/index');` and before `Route::run();`, write:

   ```php
       // the Bookshelf pages: their data comes from read-only capabilities
       Route::page('/books', 'Bookshelf/books', ['data' => ['books' => 'list_books']]);
       Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book'], 'notFound' => 'Bookshelf/notfound']);
       Route::redirect('/catalog', '/books');
   ```

5. **Write the views.** `application/views/Bookshelf/books.pug` (the [Views](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views)
   page adds the form that creates a book):

   ```pug
   extends ../default/master/site

   block title
     | Bookshelf

   block content
     section.cq-hero.cq-hero--page
       h1.cq-display Books

     section.cq-band.cq-band--tight
       .cq-inner.cq-inner--narrow
         if $books['total'] == 0
           p.cq-empty-state No books yet.
         else
           ul.cq-rows
             each $b in $books['data']
               li.cq-row
                 .cq-row-main
                   p.cq-row-title
                     a(href=$home . 'books/' . $b['id'])= $b['title']
                   p.cq-row-meta= $b['author']['name'] . ', ' . $b['published_year']
   ```

   `application/views/Bookshelf/book.pug`:

   ```pug
   extends ../default/master/site

   block title
     = $book['title'] . ' · Bookshelf'

   block content
     section.cq-hero.cq-hero--page
       h1.cq-display= $book['title']
       p.cq-lead= 'by ' . $book['author']['name'] . ', ' . $book['published_year']
   ```

   `application/views/Bookshelf/notfound.pug`:

   ```pug
   extends ../default/master/site

   block title
     | Not found · Bookshelf

   block content
     section.cq-hero
       h1.cq-display Not found
       p.cq-lead= $message
       .cq-cta
         a.btn.btn-primary(href=$home . 'books') All books
   ```

6. **Try every route.** Run:

   ```bash
   curl -s http://localhost:8080/helloworld
   ```

   It prints `Hello World` (the template's own closure route). Open `http://localhost:8080/books`: the five books,
   *A Wizard of Earthsea* first, each with its author and year. Open `http://localhost:8080/books/3`: the title
   "Kindred" and "by Octavia E. Butler, 1979". Then:

   ```bash
   curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/books/999
   curl -s -i http://localhost:8080/catalog | grep -i "^location"
   curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/nothing
   ```

   They print `404` (the "Not found" page with "There is no book #999"), `Location: http://localhost:8080/books`
   and `404`.

**Check**

- [ ] `/books` lists the books and `/books/3` shows one.
- [ ] `/books/999` and `/books/abc` show "Not found" with a 404 status.
- [ ] `/catalog` answers `302` with `Location: .../books`.
- [ ] An address no route declares answers `404`.

## <a name='basicroute'></a>How a request finds its route

`Route::run()`, the last line of the `try` block, compares the request with the routes in the order they are declared:

1. The HTTP method must be the same. `HEAD` is answered as `GET`. A form sends `PUT` or `DELETE` with a hidden
   `_method` field ([HTML form methods](#htmlformmethods)).
2. The path must have the same number of segments, and each fixed segment must be identical. A `{name}` segment
   matches any one segment. Leading and trailing slashes do not count, nor does the query string.
3. The **first** route that matches wins: declare `/books/new` before `/books/{id}`, or `/books/{id}` answers
   `/books/new` with the id `new`.
4. Nothing matches: `404` (`[ERROR 1005] Page Not Found`, or `{"error":{"code":1005,"message":"Page Not Found"}}` to a
   JSON request). The address exists with other methods: `405` with an `Allow` header
   (`Invalid Http Request Method: this address answers GET`).

A `POST`, `PUT` or `DELETE` that is not JSON is checked for its CSRF token before any route runs: without it the answer
is `403` `[ERROR 3000] Security Error - Cross Site Forgery`, whatever the address. `Route::webhook` addresses (checked by
their signature) and `Route::mcp` addresses (2.19.1: a post without a personal access token answers `401` with
`WWW-Authenticate`) skip it.

## <a name='parameterroute'></a>Route variables

`{name}` in a route captures one segment of the address:

```php
Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book']]);
```

+ In a `Route::page`, the variables become the inputs of the `data` capabilities (`get_book` gets `id`) and variables
  of the view (`$id`).
+ In `Route::form`, `Route::download`, `Route::capability` and `Route::redirect`, they become inputs or fill the
  `{name}` of the target, the same way.
+ In `Route::action`, they become inputs too. Everywhere the route variable wins over a query string value of the same
  name: `/books/3?id=9` gives `id = 3` (2.21.2; in 2.21.0 and 2.21.1, `Route::action` and `Route::capability` gave `9`).
+ In a controller you keep, read them with `$this->request->fetch('id')`
  ([Request](https://github.com/caligrafy/caligrafy-quill/wiki/3.-Request)). Since 2.21.7, on a `GET`, a query string value of
  the same name never replaces it.

A variable is always a string, and the route does not check it: `/books/abc` reaches `get_book`, whose `integer` rule
refuses it.

## <a name='pageroutes'></a>Page routes: `Route::page`

`Route::page($route, $view, $options)` answers a `GET` with a Pug view, through the framework's page controller.

```php
Route::page('/', 'default/index');
Route::page('/books', 'Bookshelf/books', ['data' => ['books' => 'list_books']]);
Route::page('/books/{id}', 'Bookshelf/book', ['data' => ['book' => 'get_book'], 'notFound' => 'Bookshelf/notfound']);
Route::page('/books/new', 'Bookshelf/new', ['signedIn' => true, 'comeBack' => true]);
Route::page('/admin/books', 'Bookshelf/admin', ['level' => 1, 'data' => ['books' => 'list_books']]);
Route::page('/about', 'default/about', ['with' => ['title' => 'About the Bookshelf']]);
Route::page('/join', 'Bookshelf/join', ['visitorsOnly' => '/books']);
Route::page('/books', 'Bookshelf/books', ['data' => ['books' => 'list_books'], 'query' => ['sort' => 'title']]);
```

| Option | Default | What it does |
| --- | --- | --- |
| `data` | none | `name => 'capability'`: calls each capability as the person who opens the page and gives the result to the view as `$name`. Its inputs are the query string and the route variables; the route variables win (`/books/3?id=9` gives `id = 3`). `name => ['capability', ['author_id' => 2]]` gives fixed inputs instead. Only read-only capabilities: a capability that changes data, or does not exist, stops the page with an error that names it |
| `signedIn` | `false` | `true`: visitors are sent to `/login` |
| `comeBack` | `false` | `true`, with `signedIn` or `level`, or when a `data` capability needs someone: visitors go to `/login?return=<this page, with its query string>`, and `Route::auth` brings them back after signing in (2.20.0) |
| `visitorsOnly` | none | a path: people already signed in are sent there (a sign-up or landing page) (2.20.0) |
| `query` | none | what the view gets of the query string: `'query' => ['show']` gives `$show`, a string, `''` when absent (2.20.0); `'query' => ['app' => 'index']` gives `$app`, `'index'` when absent; the two can be mixed (2.21.0). A route variable of the same name wins |
| `level` | `0` | people whose level (the `permissions` column of `users`) is lower are sent to `/notAuthorized`, visitors to `/login` |
| `with` | none | fixed values for the view: `['with' => ['title' => 'Books']]` |
| `notFound` | none | a view shown with a `404` when a `data` capability refuses (not found, or inputs it refuses). It gets the route variables, the `with` values, `$message`, `$authorized` and `$user` |

`signedIn`, `level` and `visitorsOnly` need `Auth::authentication('User', 'users');` in `web.php`; without it, opening
the page stops with an error that says so.

**What the view receives**: the route variables, the names listed in `query`, the `with` values, the `data` results
(plain arrays: `$book['title']`), `$authorized` (true when someone is signed in) and `$user` (`id`, `username`,
`permissions`, or `null`). The rest of the query string stays out of the view: a `data` capability gets it as inputs.
`authorized` and `user` are reserved names: a `data`, `with` or `query` entry with one of them is an error.

**When a capability refuses the page's data**:

| The capability | The answer |
| --- | --- |
| needs someone signed in, nobody is | a redirect to `/login` (`comeBack`: with `?return=`), with the authentication module; else `403` |
| refuses the person (`forbidden`) | `403` `[ERROR 1006] Forbidden` |
| finds nothing, or refuses the inputs | the `notFound` view with `404`, else `404` `[ERROR 1005] Page Not Found` |

A request with `Accept: application/json` gets the view's data as JSON instead of the page.

## <a name='declarativeroutes'></a>Forms, sign-in, webhooks, downloads, redirects and everything else

One line each, calling a capability:

```php
Route::form('/books', 'create_book', ['success' => '/books/{id}', 'flash' => 'Book added']);   // a form's POST
Route::auth(['home' => '/books']);                                                          // /login, /logout, /register
Route::webhook('/stripe/events', 'record_payment', ['verify' => 'stripe']);                  // events another service posts
Route::download('/books.csv', 'list_books', ['filename' => 'books.csv']);                   // a read-only capability as a file
Route::download('/photos.zip', 'list_photo_files', ['as' => 'zip', 'root' => 'public/uploads/photos']);   // its files as one ZIP (2.22.0)
Route::redirect('/old/books/{id}', '/books/{id}', 301);                                     // an address that moved
Route::action('/authors/{author_id}/books', 'open_author_books');                           // what a page or a form cannot say
```

Every option, with a complete example of each:
[Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes).

## <a name='capabilityroutes'></a>Capability routes: REST, the JS client and agents

```php
Route::capability('GET', '/api/books', 'list_books');          // one route, one capability, JSON
Route::capability('GET', '/api/books/{id}', 'get_book');       // {id} becomes the input "id"
Route::capability('POST', '/api/books', 'create_book');
Route::capabilities('/capabilities');                          // GET lists, POST /capabilities/{name} calls: the JS client of the Vue apps
Route::mcp('/mcp');                                            // AI agents: the capabilities their token allows, as MCP tools
```

They check who calls (a personal access token, or the signed-in person with the `X-CSRF-Token` header for writes),
validate the inputs and answer JSON: `{"data": ...}` with `200` (`201` for a `POST` that changes data), or
`{"error": {"code", "message", "fields"}}` with `401`, `403`, `404`, `409` or `422`.

```bash
curl -s -H "Accept: application/json" http://localhost:8080/api/books/2
```

prints `{"data":{"id":2,"title":"The Left Hand of Darkness","published_year":1969,"summary":"...","author_id":1,"created_at":"...","modified_at":"...","author":{"id":1,"name":"Ursula K. Le Guin",...}}}`
(with `Route::capability('GET', '/api/books/{id}', 'get_book');` in `web.php`).
More: [REST](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#rest)
and [REST API](https://github.com/caligrafy/caligrafy-quill/wiki/9.-Helpers-,-Forms-&-REST-API#restapi).

## Reference

All are static methods of `Caligrafy\Route` (`use Caligrafy\Route;` at the top of `web.php`).

| Method | Answers | What it does |
| --- | --- | --- |
| `page($route, $view, $options = [])` | GET | a Pug view with data from read-only capabilities ([above](#pageroutes)) |
| `form($route, $capability, $options = [])` | POST (or PUT, DELETE) | a form's post calls a capability, then redirects |
| `auth($options = [])` | several | `/login`, `/logout`, `/register`, `/notAuthorized` (needs `Auth::authentication(...)` before it) |
| `webhook($route, $capability, $options)` | POST | events another service posts, signature checked, no CSRF token |
| `download($route, $capability, $options = [])` | GET | a read-only capability's result as a CSV or JSON file |
| `redirect($from, $to, $status = 302, $options = [])` | GET | sends the visitor to `$to` (`301`, `302`, `303`, `307` or `308`); `['keepQuery' => true]` takes the query string along |
| `action($route, $capability, $options = [])` | GET, or `method` | a web-only capability answers: a view, a redirect, JSON or text ([Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#action)) |
| `capability($method, $route, $name)` | the method given | one capability as JSON (`GET`, `POST`, `PUT` or `DELETE`) |
| `capabilities($prefix = '/capabilities')` | GET, POST | the listing and `POST {prefix}/{name}` for the JS client |
| `mcp($route = '/mcp')` | POST (GET, DELETE: 405) | the MCP endpoint for AI agents |
| `notifications()` | GET, POST | the confirm and unsubscribe pages of notification emails |
| `bots()` | POST, DELETE | the data routes of the Watson bot apps (`/__bots__/...`) |
| `get`, `post`, `put`, `delete($route, $method)` | that method | a closure, `'Controller'` or `'Controller@action'`, for what existing projects declare that way ([Other ways](#controllerroute)) |
| `run()` | | matches the request and runs its route: the last line of the `try` block |
| `routes()` | | the routes declared so far: `[['method' => 'GET', 'route' => 'books/{id}'], ...]` (tests) |
| `handler($method, $route)` | | the closure or `'Controller@action'` of a declared route (tests) |
| `reset()` | | forgets every route (tests) |
| `Route::$currentRoute`, `Route::$currentBind` | | the matched pattern (`books/{id}`) and its variables (`currentRoute()`, `currentBind()`) |

Errors of the router (each one also answers JSON to a JSON request):

| Status | Error | When |
| --- | --- | --- |
| `404` | `1005` Page Not Found | no route matches, or a page's data is not found |
| `405` | `1000` Invalid Http Request Method | the address exists with other methods (`Allow` header) |
| `403` | `3000` Cross Site Forgery | a form post without the session's `_token` |
| `403` | `1006` Forbidden | a page's capability refuses the person |
| `404` | `1001` Invalid Controller or Action | a `'Controller@action'` route whose class or method does not exist |
| `401` | `1004` Access Denied | a JSON request to `Route::action` or a controller route without `X-CSRF-Token` or a token that grants `*` |

## <a name='controllerroute'></a>Other ways: closures and controller routes

`Route::get`, `post`, `put` and `delete` take a closure or a controller. A new request does not need them: the routes
above cover every case, with `Route::action` for what is neither a page nor a form. They stay for existing projects and
for the routes a new project's `web.php` ships: see
[Controllers](https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers#when).

```php
Route::get('/helloworld', function () { echo 'Hello World'; });          // a closure
Route::get('/authors/{author_id}/books', 'BookController@byAuthor');      // a controller and its action
Route::get('/reports/{id}', 'Shop\ReportController@show');                // a namespaced controller
Route::get('/books', 'BookController');                                   // no action: index()
```

+ `'Name@action'` finds a declared class `Name` first (global or fully qualified, a leading `\` is accepted), then
  the example controllers of `Caligrafy\Controllers` (`'ClientController'`); a class or action that does not exist
  answers `404` `[ERROR 1001]`. More: [Namespaced controllers](https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers#namespacedcontrollers).
+ A **controller route** refuses a JSON request (`Accept: application/json`) unless it comes from a page of the app
  (the session cookie and the `X-CSRF-Token` header) or, with `Auth::activateAPI();` in `web.php`, from a program
  with a personal access token that grants `*` (`401` `[ERROR 1004] Access Denied: <why>` otherwise).
+ A **closure route** has no such check, and a JSON request skips the form's CSRF check. Never read or write data in
  a closure: use `Route::page`, `Route::form`, `Route::action` or a capability route.

## <a name='htmlformmethods'></a>HTML form methods

HTML forms only send `GET` and `POST`. A `POST` with a hidden `_method` field set to `PUT` or `DELETE` is routed as
that method (method spoofing). In a Pug form, `=methodField('PUT')` writes the field:

```pug
form(method='POST', action=$home . 'books/' . $book['id'])
  =csrf()
  =methodField('PUT')
  button.btn.btn-primary(type='submit') Save
```

It reaches `Route::put('/books/{id}', ...)` or `Route::form('/books/{id}', 'update_book', ['method' => 'PUT'])`.
`_method` is read from the form fields or the query string, never from a JSON body: a script that sends JSON uses the
real method (`fetch(url, {method: 'PUT', ...})`).

## Common mistakes

+ **A route after `Route::run();`** is never declared. Every route goes before it, in the `try` block.
+ **`/books/{id}` before `/books/new`**: `/books/new` shows the book `new` (a 404). Declare fixed addresses first.
+ **A page whose data capability writes**: `Route::page` refuses it (opening a page must not change data). Use
  `Route::form` for writes, or `Route::action` when opening an address really has to change something.
+ **Data work in a closure route**: it has no permission rules and no CSRF check for JSON calls. Write a capability.
+ **`redirect()` in a closure without `return`**: `redirect()` only sends a `Location` header; code after it still
  runs. `Route::redirect` has no such problem.
+ **Before 2.16.0** an unknown address ran the first route of the file instead of answering 404.

## Related pages

+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes): forms, sign-in, webhooks, downloads, redirects, `Route::action`
+ [Request](https://github.com/caligrafy/caligrafy-quill/wiki/3.-Request): what a web-only capability or a controller reads from the request
+ [Controllers](https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers): existing ones, and how to move one
+ [Views](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views): Pug pages and `errors()`, `old()`, `flash()`
+ [Build once: services, capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP)
+ [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries): the query builder the capabilities use

<br /><br />
>[Next Section: Learn about Requests](https://github.com/caligrafy/caligrafy-quill/wiki/3.-Request)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/3.-Request -->

# Request

`Caligrafy\Request` holds what a request brings: its method, its address, its route variables, its fields or JSON body,
its files and its headers. You rarely read it yourself: a capability receives its inputs already collected and checked
by its route (`Route::page`, `Route::form`, `Route::action`, `Route::capability`...), and a `Context` that says who is
calling. You read the request in a web-only capability, when the answer depends on something that is not an input (a
header, how the call was made), and in the controllers you keep.

## With Claude

Describe the behavior; the `caligrafy` skill knows the request API and reads it only where the inputs are not enough.

```text
"Add GET /authors/{author_id}/books: when the author has one book, go straight to its page; otherwise list them."
```

Claude declares `author_id` in `$rules`, so the capability gets it as an input, and adds one `Route::action` line to
`application/config/routing/web.php`.

**Check**

- [ ] What can be an input is declared in `$rules`: nothing reads `$_GET`, `$_POST` or `$_FILES` for it.
- [ ] Only a capability with `webOnly: true` calls `request()`: a plain capability is also reached by REST, MCP, the command
      line and jobs, which have no such request.

## By hand

1. **Write a capability that shows what it reads.** Run
   `docker compose exec dev-box php caligrafer.php service Demo/ShowRequest`, and replace the content of
   `application/services/Demo/ShowRequest.php` with:

   ```php
   <?php

   use Caligrafy\Capability;
   use Caligrafy\Context;
   use Caligrafy\Service;
   use Caligrafy\Web;

   // show_request: the inputs a capability gets, and what it can read of the request
   #[Capability(name: 'show_request', description: 'Shows what the request carries.', public: true, webOnly: true)]
   class ShowRequest extends Service
   {
       public $rules = array('id' => '', 'title' => '', 'sort' => '');

       public function handle(array $input, Context $context)
       {
           $request = request();
           return Web::json(array(
               'input' => $input,
               'method' => $request->method,
               'uri' => $request->uri,
               'parameters' => $request->parameters(),
               'wantsJson' => $request->wantsJson(),
           ));
       }
   }
   ```

2. **Route it.** In `application/config/routing/web.php`, before `Route::run();`:

   ```php
       Route::action('/echo/{id}', 'show_request', ['method' => ['GET', 'PUT']]);
   ```

3. **Call it.** Run:

   ```bash
   curl -s "http://localhost:8080/echo/3?sort=title"
   ```

   It prints:

   ```json
   {"input":{"sort":"title","id":"3"},"method":"GET","uri":"echo/3","parameters":{"sort":"title","uri":"echo/3"},"wantsJson":false}
   ```

   `uri` is in the parameters of a `GET` because the server's rewrite rule passes the path as `?uri=` (`.htaccess`). The
   capability's inputs do not have it: only what `$rules` declares reaches `handle()`.

4. **Send a JSON body.** A JSON call to `Route::action` needs a personal access token that grants everything
   (`php caligrafer.php token create "echo test" --scopes "*"` prints it once) or, from a page, the `X-CSRF-Token` header:

   ```bash
   curl -s -X PUT -H "Accept: application/json" -H "Authorization: Bearer cq_..." \
        -H "Content-Type: application/json" http://localhost:8080/echo/3 -d '{"title":"Dune"}'
   ```

   It prints:

   ```json
   {"input":{"title":"Dune","id":"3"},"method":"PUT","uri":"echo/3","parameters":{"title":"Dune"},"wantsJson":true}
   ```

   Without the token it answers `401` with `{"error":{"code":1004,"message":"Access Denied: send the page's CSRF token in
   an X-CSRF-Token header (pages, with the session cookie) or Authorization: Bearer <personal access token> (programs
   and agents)"}}`.

**Check**

- [ ] `input` has the query string or the body and the route variable, as strings (`"3"`).
- [ ] A form post's parameters include `_token` and `_method`; a JSON body's parameters are the decoded body.

## <a name="accessrequest"></a>Getting the request

+ In a web-only capability (`#[Capability(..., webOnly: true)]`, served by
  [`Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#webonly)), a closure route or a helper: `request()`, which builds a
  new `Request` each time.
+ In a controller you keep: `$this->request`, built once when the controller is created.
+ In any other capability: never. Its inputs come from the route (the fields, the query string and the route variables),
  and `$context` says who calls (`$context->user`, `$context->userId()`). The route variables win over the query string on
  every declared route: `/echo/3?id=9` gives `id = 3` (`Route::action` and `Route::capability` since 2.21.2). Still check a
  route variable that decides what is reached against the person.

## <a name="requestproperties"></a>Properties

| Property | What it holds | Example for `PUT /echo/3` with `{"title":"Dune"}` |
| --- | --- | --- |
| `$method` | the HTTP method in upper case, after `_method` (a `POST` with `_method=PUT` is `PUT`) | `PUT` |
| `$uri` | the path without its leading and trailing slashes, `/` for the home page | `echo/3` |
| `$fullUri` | the path, `?`, and the parameters as a query string | `echo/3?title=Dune` |
| `$uriComponents` | the segments of the path | `['echo', '3']` |
| `$parsedURI` | the same segments, from `parsePath()` | `['echo', '3']` |
| `$uriParameters` | `GET`: the query string (`$_GET`); `POST`, `PUT`, `DELETE`: the form fields, else the decoded JSON body | `['title' => 'Dune']` |
| `$parameters` | `$uriParameters`, or the route variables when there are none | `['title' => 'Dune']` |
| `$currentRoute` | the pattern of the matched route | `echo/{id}` |
| `$currentBind` | the route variables, plus the query string for a `GET` route; a route variable is never replaced (2.21.7) | `['id' => '3']` |
| `$fetch` | `$currentBind` as an object: `$this->request->fetch->id` | `{id: "3"}` |
| `$host` | the `Host` header | `localhost:8080` |
| `$authorization` | the `Authorization` header | `Bearer cq_...` |
| `$accept` | the `Accept` header | `application/json` |
| `$acceptEncoding`, `$acceptLanguage`, `$cache`, `$cookie`, `$userAgent` | those headers | |
| `$token` | the personal access token row, once `authorizeApiRequest()` checked it (`null` before) | |

## <a name="requestmethods"></a>Methods

| Method | Returns |
| --- | --- |
| `fetch($name)` | a route variable (or, for a `GET` route, a query string value) by name; by position when `$name` is an integer (`fetch(1)` is the first); `''` when there is none |
| `parameters()` | the request's parameters again (as `$uriParameters`) |
| `files($field)` | the `$_FILES` entry of a file input (`name`, `type`, `tmp_name`, `error`, `size`), `[]` when there is none |
| `wantsJson()` | `true` when `Accept` contains `application/json` and not `text/html` (an API call) |
| `bearer()` | the value after `Bearer ` in `Authorization`, else `null` |
| `authorizeSessionRequest()` | `true` when the `X-CSRF-Token` header (or a `_token` field) equals the session's CSRF token: a page of this app |
| `authorizeApiRequest($scope = '*')` | `true` for a personal access token that grants `$scope`, or the legacy API key while `LEGACY_API_KEY` is not `false` |
| `apiRefusal()` | why a JSON call to `Route::action` or a controller route was refused (the text after `Access Denied:`) |
| `isLegacyApiKey($key)`, `Request::legacyKeysDisabled()` | whether a value is this app's legacy API key; whether `LEGACY_API_KEY=false` turned those keys off |
| `forClient()` | what a client app's page may see of the request (2.19.1): `method`, `host`, `uri`, `fullUri`, `uriComponents`, `uriParameters` (the query string, without `_token`), `parameters`, `parsedURI`, `currentRoute`, `fetch` and `acceptLanguage`. Never the `Cookie` (the session id), the `Authorization` header or a `POST` body. The `Client/app` view gives it to the app's script as `env.request` |

**The CSRF check.** Building a `Request` for a `POST`, `PUT` or `DELETE` checks the CSRF token, and stops with `403`
`[ERROR 3000] Security Error - Cross Site Forgery` when the `_token` field is missing or wrong. It is skipped when the
request carries a bearer token, sends the session's token in `X-CSRF-Token`, asks for JSON (`wantsJson()`), posts to a
`Route::webhook` address, a `Route::mcp` address (2.19.1: without a personal access token it answers `401` JSON-RPC
with `WWW-Authenticate`, never as the session's user) or the notifications unsubscribe page, or comes from a `User-Agent` listed in
`APPROVED_AGENTS`. The token is read from the form fields only, never from a JSON body.

## Common mistakes

+ **`fetch('id')` is a string.** Compare with `==` or cast it: `(int) $this->request->fetch('id')`. Give it to a
  capability with an `integer` rule rather than checking it yourself.
+ **`fetch('id')` on a `GET` with `?id=9`** gives the route variable: since 2.21.7 the query string never replaces it. Read the
  query string value under another name.
+ **`fetch()` of a query string value on a `POST` route** returns `''`: the query string is only merged for `GET`
  routes. Read the body with `parameters()`.
+ **A JSON body without `Accept: application/json`** fails the CSRF check (`[ERROR 3000]`): the token is only read
  from form fields. Send `Accept: application/json` and `X-CSRF-Token` (pages) or a bearer token (programs).
+ **`fetch()` from the browser sends `Accept: */*`**, which is not JSON: set `Accept: application/json` yourself.
  `axios` sends `application/json, text/plain, */*`, which is.
+ **Reading the request in a plain capability**: it works for the web only. REST, MCP, the command line and jobs have no
  such request; declare the input in `$rules` instead, or give it from the route with the `inputs` option of `Route::form`.
  A capability that truly needs the request is `webOnly: true`.

## Related pages

+ [Routing](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing): how a request finds its route
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#action): `Route::action` and web-only capabilities
+ [Controllers](https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers): `$this->request` in the controllers you keep
+ [Helpers, forms and REST API](https://github.com/caligrafy/caligrafy-quill/wiki/9.-Helpers-,-Forms-&-REST-API): `request()`, `csrf()`, `methodField()`
+ [Build once: services, capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#tokens): personal access tokens

<br /><br />
>[Next Section: Learn about Models](https://github.com/caligrafy/caligrafy-quill/wiki/4.-Models)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.7-Understanding-the-flow-of-information -->

A **Vue app** is one more experience of your application, next to its Pug pages, its REST API and its AI agents. Caligrafy keeps the data and the rules on the server, in capabilities; the Vue app draws the screens in the browser and calls those capabilities through a JavaScript client that Caligrafy generates. This page follows one click from a Vue app to the database and back, and compares the two kinds of Vue app Caligrafy makes.
## With Claude

```text
/caligrafy-quill:new-app app bookshelf
```
Claude scaffolds `public/bookshelf/`, generates the JS client into `public/js/capabilities.js`, wires the page route in `application/config/routing/web.php` and writes the screens with the page components. `/caligrafy-quill:new-app create bookshelf` makes a Vite single page app instead. Write the capabilities first, or in the same request (`/caligrafy-quill:new-capability`).

**Check** before you say OK:
+ The app's page opens and its browser console has no error.
+ Data comes from the generated client (`listBooks()`, `createBook()`), never from a hand-built request with an API key.
+ A refused input shows the field's message from the server.
## By hand

You follow one call of the Bookshelf app, with `curl` standing in for the browser. You need the Bookshelf tables, sample data and capabilities of [Views, steps 1 to 3](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#viewsstartup), and `Route::capabilities('/capabilities');` in `application/config/routing/web.php` (the Quickstart adds it).

**1. What the client sees.** Run:
```bash
curl -H "Accept: application/json" http://localhost:8080/capabilities
```
Expected: `{"data":[{"name":"create_book","description":"Adds a book to the Bookshelf catalog and returns it with its id and its author. ...","scope":"books:write",...,"input":{"type":"object","properties":{"title":{"type":"string","maxLength":200,...},...},"required":["title","published_year","author_id"]}},...],"csrf":"<64 characters>"}`: the capabilities this caller may use, with their inputs, and the session's CSRF token. The generated client reads this token once, then sends it with every write.

**2. A call.** Run:
```bash
curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" -d '{"id": 3}' http://localhost:8080/capabilities/get_book
```
Expected: `{"data":{"id":3,"title":"Kindred","published_year":1979,"summary":"A young woman is pulled back in time to a plantation in Maryland.","isbn":null,"author_id":2,...,"author":{"id":2,"name":"Octavia E. Butler",...}}}`: the book, with its author nested. In the Vue app this is one line, `await getBook({ id: 3 })`, which returns what is inside `data`.

**3. A refusal.** Run:
```bash
curl -X POST -H "Accept: application/json" -H "Content-Type: application/json" -d '{"title": "Lilith"}' http://localhost:8080/capabilities/create_book
```
Expected: status `422` and `{"error":{"code":"invalid","message":"Some of the inputs are invalid","fields":{"published_year":"The Published Year field is required","author_id":"The Author Id field is required"}}}`. In the Vue app, `createBook()` throws a `CapabilityError` whose `fields` is that object: one message per field, ready for the form.

**Check**
+ The same answers come from the Pug page, from REST and from an AI agent: one set of rules.
+ No API key appears anywhere: a page uses the visitor's session cookie and the CSRF token; programs and agents use a personal access token.
## Reference

### The flow

```text
Vue app (browser)                     Caligrafy (server)
-----------------                     ------------------
createBook({ title, ... })
  -> POST /capabilities/create_book   Route::capabilities('/capabilities')
     session cookie + X-CSRF-Token      -> who is calling: the signed-in user, or a visitor
                                        -> may they use it: public, scope, level
                                        -> $rules check the inputs
                                        -> handle(): the query builder reads and writes the database
  <- {"data": {...}}            201     <- the answer, the same for every channel
  <- {"error": {code, fields}}  422     <- or a refusal: invalid, unauthenticated, forbidden, not_found, conflict
```

### The two kinds of Vue app

| | Vue as a library | Vite single page app |
| --- | --- | --- |
| Created by | `php caligrafer.php app <name>` | `php caligrafer.php create <name>` |
| Lives in | `public/<name>/index.php` and `public/<name>/scripts/main.js` | `public/<name>/src/` (`.vue` files), built to `public/<name>/dist/` |
| Needs Node.js | no | yes (20.19+ or 22.12+), on your computer |
| Served by | Caligrafy: a page route renders it (view `Client/app`) and gives it `env` | `npm run dev` while you work; `dist/` once built |
| Its JS client | `public/js/capabilities.js` | `public/<name>/src/capabilities.js` |
| Good for | one screen or a few, next to Pug pages | a larger app with its own routes, components and store |
| Pages | [setting up](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.0-Setting-up-Vue.js-as-a-library), [structure](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.1-Understanding-the-structure), [routes](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.2-Routes), [requests](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.3-Requests), [forms](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.4-Forms), [validations](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.5-Validations), [components](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.6-Components) | [setting up](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.1---Setting-up-the-Vue-application), [routing](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.2-Routing-for-Single-Page-Applications), [single file components](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.3-Single-File-Components), [state](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.4-State-Management) |

### Who does what

| Caligrafy (PHP, `application/`) | Vue (JavaScript, `public/<app>/`) |
| --- | --- |
| tables, models, capabilities and their rules | screens, components, what the person types |
| who may do what: sessions, tokens, scopes, levels | showing what the server answered, and its errors |
| the page route that serves the app | the routes between the screens of a single page app |

Both kinds of app build their screens with Caligrafy's [page components](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#pagecomponents) (`layout.css`, `look.css`), so they look like the Pug pages.
## Other ways

A Vue app can call a [`Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#action) or a controller route that answers JSON, with `fetch` or axios and the headers of `apiHeaders()`: see [Requests, other ways](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.3-Requests). Capabilities replace them: the same rules then serve the pages, REST and AI agents.
## Related pages

+ [How Caligrafy works](https://github.com/caligrafy/caligrafy-quill/wiki/How-Caligrafy-Works)
+ [Build once: services, capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP)
+ [Vue.js](https://vuejs.org/)

<br/><br/>

> [Next Section: Understanding the structure](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.1-Understanding-the-structure)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.7.2-Routes -->

A Vue app as a library needs two kinds of routes on the server, both in `application/config/routing/web.php`: a **page route**, which serves the app's markup with its `env`, and the **capability routes**, which the app calls for its data. Routing between screens inside the browser is the job of a single page app ([Routing for single page apps](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.2-Routing-for-Single-Page-Applications)).
## With Claude

`/caligrafy-quill:new-app app <name>` adds the page route; `/caligrafy-quill:new-capability` adds capabilities and keeps `Route::capabilities('/capabilities')` in place. To change a route, ask: "serve the bookshelf app at /shelf, for signed-in people only".

**Check** before you say OK:
+ The page route is a `Route::page(..., 'Client/app', ...)` above `Route::run();`, with `appName` the folder in `public/`.
+ `Route::capabilities('/capabilities');` is in `web.php` once.
+ Opening the address while signed out does what was asked (the app, or the sign-in page).
## By hand

You serve the Bookshelf app of [Setting up Vue as a library](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.0-Setting-up-Vue.js-as-a-library) three ways and give it its first books from the server.

**1. The ready-made address.** The template's `web.php` serves every client app at `/apps/<name>`. Its line names the example controller; write the same address declared, and open it:
```php
    Route::page('/apps/{appName}', 'Client/app', ['query' => ['app' => 'index']]);
```
Replace the `Route::get('/apps/{appName}', ...)` line with it. Open `http://localhost:8080/apps/bookshelf`: the app opens with no route of its own. It serves any folder of `public/` whose name is made of letters, digits, `-` and `_`.

**2. Your own address.** In `application/config/routing/web.php`, above `Route::run();`, write:
```php
    // BOOKSHELF: the Vue app (public/bookshelf/index.php)
    Route::page('/bookshelf', 'Client/app', ['with' => ['appName' => 'bookshelf', 'app' => 'index']]);
```
Open `http://localhost:8080/bookshelf`: the same app, and in the console `env.authorized` and `env.user` say who is signed in.

**3. The first books from the server.** Change the route to:
```php
    Route::page('/bookshelf', 'Client/app', ['with' => ['appName' => 'bookshelf', 'app' => 'index'], 'data' => ['books' => 'list_books']]);
```
Reload, and type `env.books` in the console: `{data: Array(...), total: ..., page: 1, per_page: 20, pages: ...}`, the answer of `list_books`, in the page itself. The script can show it at once (`this.books = env.books.data`) and call the client for the next pages.

**4. The data routes.** Check that `web.php` has, once:
```php
    Route::capabilities('/capabilities');   // the capabilities for the JS client of the Vue apps
```
Run `curl -H "Accept: application/json" http://localhost:8080/capabilities`: `{"data":[...],"csrf":"..."}`.

**Check**
+ `http://localhost:8080/bookshelf` and `http://localhost:8080/apps/bookshelf` open the same app.
+ `http://localhost:8080/apps/nothere` answers `This client app does not exist...`.
## Reference

### Page routes

| Route | What it does |
| --- | --- |
| `Route::page('/bookshelf', 'Client/app', ['with' => ['appName' => 'bookshelf', 'app' => 'index']])` | serves `public/bookshelf/index.php`. Takes every option of [`Route::page`](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#parameterview): `data` (read-only capabilities, their answers in `env`), `signedIn` (visitors go to `/login`), `level`, `notFound`; `env` gets `authorized` and `user` |
| `Route::page('/apps/{appName}', 'Client/app', ['query' => ['app' => 'index']])` | serves `public/<appName>/index.php`, or `public/<appName>/<file>.php` with `?app=<file>`. `query` lists what `env` gets of the query string |
| `Route::page('/bot/{appName}', 'Client/app', ['query' => ['app' => 'index', 'botSkillId']])` | a bot app: `?botSkillId=` is its assistant |
| `Route::page('/ml/{appName}', 'Client/app', ['query' => ['app' => 'index']])` | a machine learning app |
| `Route::get('/apps/{appName}', 'Caligrafy\\Controllers\\ClientController')`, and the same for `/bot/`, `/ml/` | what the template's `web.php` ships: the same result, and `env` gets the whole query string |

`appName` and `app` must be made of letters, digits, `-` and `_`, and only files directly inside `public/<appName>/` are served; anything else shows `This client app does not exist`.

### Data routes

| Route | What it serves |
| --- | --- |
| `Route::capabilities('/capabilities')` | `GET /capabilities`: the capabilities the caller may use and the CSRF token; `POST /capabilities/<name>`: calls one. The generated JS client uses it |
| `Route::capability('GET', '/api/books', 'list_books')` | one capability at a REST address, for other programs ([Build once: REST](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP#rest)) |
## Under the hood

+ **`ClientController`** (`application/controllers/core/AI/ClientController.php`) takes the last part of the path as `appName` and `?app=` as the markup file (default `index`), then returns `view('Client/app', ...)` with the query string. A page that first chooses what to show is a web-only capability: `return Web::view('Client/app', ['appName' => 'bookshelf', 'app' => 'index', 'shelf' => $shelf]);`.
+ **A closure** `Route::get('/bookshelf', function () { return view('Client/app', ['appName' => 'bookshelf', 'app' => 'index']); });` works too, without `authorized` and `user`. `Route::page` replaces both.
+ **Controller data routes** (`Route::get('/api/shelf', 'BookController@index')` returning `api([...])`) still answer JSON, in code that has them: see [Requests, other ways](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.3-Requests). Capabilities replace them.
## Common mistakes

+ **`appName` that is not the folder name**: `This client app does not exist`.
+ **A `data` capability that writes**: `Route::page` accepts only read-only capabilities (`500` on every visit).
+ **Expecting the query string in `env` with `Route::page`**: only the names listed in its `query` option reach it.
+ **Two `Route::capabilities` lines**: keep one.
## Related pages

+ [Routing](https://github.com/caligrafy/caligrafy-quill/wiki/2.-Routing)
+ [Views: `Route::page`](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#parameterview)
+ [Understanding the structure](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.1-Understanding-the-structure)

<br /><br />

> [Next Section: Requests](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.3-Requests)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.7.5-Validations -->

**Validation** decides whether what a person typed is acceptable. In Caligrafy it happens once, on the server, in the capability's `$rules`: the same rules answer the Vue app, the Pug pages, REST and AI agents, and the messages come back one per field. A Vue app shows those messages; it can also check the obvious cases before sending, from the same rules, so the person waits less.
## With Claude

Ask for the rule, not for the screen: "a book's title needs at least 2 characters". Claude changes `$rules` in the capability (`/caligrafy-quill:new-capability` knows the [rules](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation)), runs `php caligrafer.php client` again, and the forms show the new message with no change.

**Check** before you say OK:
+ The rule is in the capability's `$rules`, not only in the Vue script.
+ `php caligrafer.php call create_book title=D author_id=2 published_year=1987` answers `invalid` with the message.
+ The Vue form shows that message under the field.
## By hand

You add a rule to `create_book` and show it in the Bookshelf app of [Forms](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.4-Forms), then add a check before sending. Commands run in the project folder with the Docker server.

**1. The rule.** In `application/services/Bookshelf/CreateBook.php`, change the title's rule in `$rules` to:
```php
        'title' => 'required|min_len,2|max_len,200',
```

**2. Try it from the command line.** Run:
```bash
docker compose exec dev-box php caligrafer.php call create_book title=D author_id=2 published_year=1987
```
Expected:
```json
{
    "error": {
        "code": "invalid",
        "message": "Some of the inputs are invalid",
        "fields": {
            "title": "The Title field needs to be at least 2 characters"
        }
    }
}
```

**3. Update the client.** Run `docker compose exec dev-box php caligrafer.php client public/js/capabilities.js`. The rules are on the server, so the functions do not change, but `GET /capabilities` now describes `title` with `"minLength": 2` (and `published_year` with `"minimum": 1450` and `"maximum"`: this year).

**4. See it in the app.** Open `http://localhost:8080/bookshelf`, type `D`, choose an author, type `1987`, press **Add book**: `The Title field needs to be at least 2 characters` appears under the title. The `addBook()` of [Forms](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.4-Forms) already puts `e.fields` in `errors`.

**5. Check before sending.** In `public/bookshelf/scripts/main.js`, add this function above `const app = Vue.createApp({`:
```js
// The obvious cases, from the capability's own description: the server still decides
function check (schema, input) {
    const errors = {}
    for (const [field, rule] of Object.entries(schema.properties)) {
        const value = input[field] === null || input[field] === undefined ? '' : String(input[field])
        if ((schema.required || []).includes(field) && value === '') errors[field] = 'Required'
        else if (rule.minLength && value.length < rule.minLength) errors[field] = 'At least ' + rule.minLength + ' characters'
        else if (rule.maxLength && value.length > rule.maxLength) errors[field] = 'At most ' + rule.maxLength + ' characters'
        else if (rule.minimum !== undefined && value !== '' && Number(value) < rule.minimum) errors[field] = 'At least ' + rule.minimum
        else if (rule.maximum !== undefined && value !== '' && Number(value) > rule.maximum) errors[field] = 'At most ' + rule.maximum
    }
    return errors
}
```
At the end of `mounted()`, after `await this.load(1)`, add:
```js
        this.schema = (await this.api.capabilities()).find(c => c.name === 'create_book').input
```
At the start of `addBook()`, before `this.errors = {}`, add:
```js
            const found = this.schema ? check(this.schema, this.book) : {}
            if (Object.keys(found).length) { this.errors = found; return }
```
Reload, type `D`, choose an author, type `1987`, press **Add book**: `At least 2 characters` appears at once, without a call (the network panel shows no `POST /capabilities/create_book`). A year of `987` shows `At least 1450`.

**Check**
+ Removing the check of step 5 still refuses the book, with the server's message: the server is the rule.
+ The Pug page `/books` and `curl -X POST ... /capabilities/create_book` refuse the title `D` with the same message.
## Reference

### Where each part lives

| Part | Where | Effect |
| --- | --- | --- |
| `$rules` | the capability | GUMP rules per input: `required`, `max_len,255`, `min_len,2`, `integer`, `valid_email`, `exists,authors.id`, `unique,books.isbn`... ([all rules](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation)). Only these inputs reach `handle()` |
| `$filters` | the capability | applied before the rules: `trim`, `sanitize_string`... |
| `$descriptions` | the capability | what each input is, in the schema clients and agents read |
| `ServiceError::invalid(['author_id' => 'There is no such author'])` | `handle()` | a refusal decided by code, with the same shape |
| `e.fields` | the Vue app | `{field: message}` of a `CapabilityError` whose `code` is `invalid` |
| `capabilities()` | the Vue app | each capability's `input`: a JSON schema with `required`, `maxLength`, `minLength`, `format` (email, uri), `enum`, `type` |

### Messages

Each field gets one message, the first rule it breaks, in GUMP's words with the field's name: `The Published Year field is required`, `The Title field needs to be at least 2 characters`, `The Published Year field needs to be a numeric value, equal to, or higher than 1450`. The whole refusal is `422` with `{"error": {"code": "invalid", "message": "Some of the inputs are invalid", "fields": {...}}}`.
## Other ways: a controller that validates

A controller in older code validates with `$this->check()` and answers with `api()`:
```php
$errors = $this->check($this->request->parameters(), array('title' => 'required|max_len,200', 'author_id' => 'required|integer'));
if ($errors !== true) {
    http_response_code(422);
    return api(array('error' => true, 'message' => 'Some of the inputs are invalid', 'errors' => $errors));
}
```
`fetch` then gets `response.status === 422` and the payload from `await response.json()`; axios rejects and puts it in `error.response.data`. The rules then live in that controller only: a capability gives them to every channel.
## Common mistakes

+ **The rule only in JavaScript**: REST, agents and anyone with `curl` skip it. Put it in `$rules`.
+ **A client check stricter than the server**: people are refused for no reason. Build it from `capabilities()`, as in step 5.
+ **An input sent but missing from `$rules`**: it is dropped before `handle()`. Add it with `''` (no rule) if it needs none.
## Related pages

+ [Validation rules](https://github.com/caligrafy/caligrafy-quill/wiki/6.-Validation)
+ [Forms](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.4-Forms)
+ [Vue form bindings](https://vuejs.org/guide/essentials/forms.html)

<br /><br />

> [Next Section: Components](https://github.com/caligrafy/caligrafy-quill/wiki/9.7.6-Components)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.5-Security-and-Upgrading -->

This page has two parts: the settings an application needs before it goes online, with what the framework protects by
itself, and how to bring an existing project to a new release of Caligrafy Quill (`php caligrafer.php update`).
## With Claude

| You want | Ask |
|---|---|
| to know whether the project is ready for production | `/caligrafy-quill:deploy` (a read-only check: Dockerfile, `composer.lock`, scripts safe to run again, no secrets in git, `APP_DEBUG=false` online) |
| a review of your code for security mistakes | "review my code" (the `caligrafy-reviewer` agent: SQL built from input, CSRF, uploads, exposed secrets...) |
| the latest release | `/caligrafy-quill:update` (or `/caligrafy-quill:update 2.19.0`) |

`/caligrafy-quill:update` runs `php caligrafer.php update --check`, shows you what it changes, runs
`php caligrafer.php update`, merges each `<file>.caligrafy-new` into your version, then runs `version`, `doctor`,
`upgrade --local` and `platform install`, and checks the sign-in flows and the forms. It commits only with your OK.

**Check**

+ `php caligrafer.php version` prints the new version.
+ `find . -name '*.caligrafy-new' -not -path './vendor/*' -not -path './backups/*'` prints nothing.
+ `php caligrafer.php doctor` has no `FAIL`.
+ Sign in, sign out, sign up and one form work from a private window.
## By hand: the production settings

**1. The production `.env`.** Online, the app reads its own `.env` (on Caligrafy Cloud the database settings and keys
are written for you; set the rest with `php caligrafer.php cloud secret set <app> KEY=value`). Give it:

```text
APP_ROOT=
APP_ENV=production
APP_PROTOCOL=https
APP_DEBUG=false
APP_URL=https://bookshelf.example.com
LEGACY_API_KEY=false
DB_ACTIVATE=true
```

and its own `APP_KEY` and `API_KEY`: `php caligrafer.php generatekeys` prints a new pair. Never reuse your computer's
keys, never commit a `.env`.

| Setting | Why |
|---|---|
| `APP_ENV=production` | the live Stripe keys, Google Analytics, the class map's production checks |
| `APP_DEBUG=false` | errors show no details to visitors, and Phug's debug mode is off: pages about three times faster (2.19.0) |
| `APP_PROTOCOL=https` | the links the app builds start with `https://` |
| `APP_URL` | the links of emails sent by jobs, the return addresses of payments, `og:url` |
| `LEGACY_API_KEY=false` | only personal access tokens open the API (Caligrafy Cloud sets it) |

**2. Leave the speed settings as they are.** They are on by default; each has a setting that turns it off, for when
something breaks:

| On by default | What it does | Turned off by |
|---|---|---|
| the views cache | each Pug view is compiled to PHP once, again only when it or a file it includes changes (2.17.0) | `VIEW_CACHE=false` |
| the Phug Optimizer | a compiled view runs without building Phug's compiler (2.19.0) | `VIEW_OPTIMIZER=false` |
| lazy sessions | a `GET` without a session cookie gets a session only when it needs one (2.19.0) | `SESSION_LAZY=false` |
| the class map | each class of `application/` is loaded when first used (2.18.0) | `CLASS_MAP=false` |
| `.env.php` | the settings are read from `.env.php` instead of parsing `.env` (2.19.0) | `php caligrafer.php env clear` |

**3. Compile `.env`.** With the production image (Caligrafy Cloud, Coolify, Docker), the deploy step does it at every
start: nothing to do. On a server without the image, run after each change to `.env`:

```bash
php caligrafer.php env cache
```
```text
 .env compiled to .env.php: pages read it without parsing .env (php caligrafer.php env clear removes it)
```

`.env.php` is used only while `.env` is exactly what it was compiled from: an edited `.env` is read as it is (slower,
still right) until the next `env cache`. `.gitignore` lists `.env.php`: never commit it.

**4. Check the server.** Run, with your address:

```bash
curl -I https://bookshelf.example.com/.env
curl -I https://bookshelf.example.com/caligrafer.php
```

Both must answer `403` or `404`. Then run `php caligrafer.php doctor` on the server (or `php caligrafer.php doctor
--env .env.production` on your computer): no `FAIL`, Stripe in live mode when the app takes payments.

**Check**

+ `APP_DEBUG=false`, `APP_ENV=production` and keys of their own in the production `.env`.
+ `.env`, `.env.php` and `caligrafer.php` are not served.
+ `git ls-files | grep -E '(^|/)\.env($|\.)' | grep -v '\.env\.example$' | grep -v '^framework/settings/'` prints nothing.
## <a name="upgrading"></a>By hand: upgrading an existing project

A project made with the current release has nothing to do. Updating moves the `framework/` folder and the release's
other files to the new version; the `application/` folder, copied from `framework/settings/application` when the
project was made, is **yours**, and `upgrade` brings its untouched files up to date.

The commands run in the Docker server of your project; without Docker, drop `docker compose exec dev-box`.

**1. Start from a clean state.** Run `git status --short`: commit what is there first, so that the update is one change
you can review.

**2. See what changes.**

```bash
docker compose exec dev-box php caligrafer.php update --check
```

It lists what it would replace, add and keep, the new settings and packages. Up to date, it prints
` Caligrafy Quill 2.21.6 is the latest: nothing to update. php caligrafer.php upgrade checks application/.`

**3. Update.**

```bash
docker compose exec dev-box php caligrafer.php update            # the latest release
docker compose exec dev-box php caligrafer.php update 2.21.6     # or a given one
```

Run it whole (not through `| tail`: it exits with `1` when something did not finish, and its last lines run
`upgrade --apply`). Everything it replaces is copied first to `backups/caligrafy-update-<from>-to-<to>-<time>/`.

**4. Merge every `.caligrafy-new`.** A file you changed is kept, with the release's version next to it:

```bash
find . -name '*.caligrafy-new' -not -path './vendor/*' -not -path './backups/*'
```

For each one, compare (`diff <file> <file>.caligrafy-new`), write the merged result into `<file>` (your changes plus the
release's new lines and fixes), then delete the `.caligrafy-new`.

**5. Check.**

```bash
docker compose exec dev-box php caligrafer.php version            # Caligrafy Quill <the new version>
docker compose exec dev-box php caligrafer.php platform install   # the framework tables of the new release; safe to run again
docker compose exec dev-box php caligrafer.php upgrade --local    # nothing outdated left in application/
docker compose exec dev-box php caligrafer.php doctor             # no FAIL
docker compose exec dev-box php caligrafer.php test               # when tests/ has tests
```

Then open the main pages, sign in, sign out and sign up, and send each form from a private window (no session cookie).
Read the release notes of every version you passed
(`https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-<version>`) and do what they ask of projects.

**6. Commit and deploy.** Commit (`Caligrafy Quill <from> to <to>`), push, then `docker compose exec dev-box php caligrafer.php cloud deploy <app>`
(or the deploy of your own server). Delete `backups/` once you are done: git ignores it, the production image leaves
it out, and since 2.19.1 the root `.htaccess` refuses it too.

**Check**

+ `php caligrafer.php version` is the new version, here and online.
+ No `.caligrafy-new` file is left.
+ The sign-in flows and the forms work from a fresh session.

**From 2.24.1 to 2.25.0.** A Snap card no longer shows a whole page (G163): give the main lists and records card views (`/caligrafy-quill:assistant` writes them in `application/views/snap/`; `php caligrafer.php snap views` lists them). Until then those cards are designed from their data. Nothing else changes.

**From 2.24.0 to 2.24.1.** Nothing to change; tests that fake the planner pass again (G162).

**From 2.23.0 to 2.24.0.** Nothing to change: `server` and `quickstart` print the ports of your `docker-compose.override.yml`, and `php caligrafer.php server start` works by hand.

**From 2.22.1 to 2.23.0.** `update` adds `anthropic-ai/sdk` to `composer.json`; run `php caligrafer.php platform install` for Snap's tables (a deploy does it too). Nothing else changes until you add `Route::snap();` ([Snap Cards and the assistant](https://github.com/caligrafy/caligrafy-quill/wiki/Snap-Cards-and-the-Assistant)).

**From 2.22.0 to 2.22.1.** Nothing to change for builds: the new `Dockerfile` runs Composer without plugins. To turn it off for `composer install` on your computer too, set `"nodejs-php-fallback/nodejs-php-fallback": false` in `composer.json` (under `config.allow-plugins`): `update` does not change it for you, because it runs the updater of the release you come from and keeps a value the project already has.

**From 2.21.9 to 2.22.0.** stripe-php 23: only code of your own that calls `Stripe::setAccountId()` or serializes Stripe objects changes (see the [release notes](https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.22.0)).

**From 2.21.8 to 2.21.9.** Nothing to change in a project. `cloud create` no longer needs `--repo` in the `dev-box` when the project has a GitHub `origin`.

**From 2.21.7 to 2.21.8.** A number field now answers 422 to a list or `true`; a token needs a user that exists.

**From 2.21.6 to 2.21.7.** A `GET` route variable is never replaced by the query string, in controllers too; send a value in the query string under another name.

**From 2.21.5 to 2.21.6.** In a client app made earlier, load `app.js` with a version so a deploy reaches every browser:
`<?php echo APP_SERVICE_ROOT.'app.js?v='.@filemtime(PUBLIC_PATH.'js/services/app.js'); ?>`.

**From 2.21.4 to 2.21.5.** Nothing to change: client apps' scripts now carry a version that changes at each deploy.

**From 2.21.3 to 2.21.4.** Nothing to change.

**From 2.21.2 to 2.21.3.** Nothing to change. If you built face sign-in from the recipe, add its `mayChangeSignIn()` check:
without it, a session opened with a face alone (a photo can pass) can replace the enrolled face.

**From 2.21.1 to 2.21.2.** On a `GET`, `Route::action` and `Route::capability` now keep the route variable when the query
string has the same name (`/books/3?id=9` is the book 3). A passkey sign-in follows `Route::auth`'s `level`.

**From 2.21.0 to 2.21.1.** A JSON call to `Route::action` needs the page's `X-CSRF-Token` or an API token, signed in or
not. Nothing to change if your pages send it.

**From 2.20.0 to 2.21.0.** Nothing to change: `Route::action`, web-only capabilities and `Route::bots` are new, and
existing controllers keep working. Moving one is optional:
[Controllers](https://github.com/caligrafy/caligrafy-quill/wiki/8.-Controllers#controllerstartup).

**From 2.19.8 to 2.20.0.** Nothing to change: new options on `Route::page`, `Route::form`, `Route::redirect`, and
`Route::auth` follows `/login?return=<a page of this site>` after signing in.

**From 2.19.7 to 2.19.8.** The session cookie is `HttpOnly`, and `Secure` on HTTPS (directly or behind a load balancer
that sends `X-Forwarded-Proto: https`). Nothing to change, unless JavaScript of yours read the session cookie: use
`X-CSRF-Token` and the session instead.

**From 2.19.0 to 2.19.1.** No new tables. `update` replaces an untouched root `.htaccess` (it now refuses `backups/`)
and adds the new `.gitignore` lines (every `.env.*` file but `.env.example`). Vue apps get `env.request` without the
session cookie or the `Authorization` header (`request()->forClient()`). A Vite SPA made before 2.19.1 keeps its own
`src/common/app.js` and `src/main.js`: remove its `VITE_API_KEY`, as
[the SPA pages](https://github.com/caligrafy/caligrafy-quill/wiki/9.8.1---Setting-up-the-Vue-application) show.

**From 2.18 to 2.19.** No new tables. Sessions start only when used: a page with a form must print `=csrf()`, and code
that reads `$_SESSION['token']` on a `GET` reads `session('token')`. A model that declares its own `find()` keeps it for
`$book->find()`, but `Book::find()` then fails: use `Book::query()->find()`. Pug errors show their line only with
`APP_DEBUG=true` (set it on your computer). Moving controllers to declared routes is optional.
## <a name="checklist"></a>Reference: the production checklist

+ **Server files are not served.** `curl -I https://<your-host>/.env` answers `403` or `404`. The `.htaccess` files of
  Caligrafy deny dotfiles (`.env`, `.env.php`, `.git`...), the server-side folders and the tooling files, and prevent
  scripts in `public/uploads` from running. Keep them (they need `mod_rewrite` and `AllowOverride FileInfo` or `All`),
  or write the same rules for nginx.
+ **`APP_ENV=production`, `APP_DEBUG=false`**, keys of their own (`generatekeys`), no `.env` or `.env.php` in git
  (the `.gitignore` of the project also leaves out `.env.production`, `.env.testing` and every other `.env.*` but
  `.env.example`, 2.19.1).
  Changing the `APP_KEY` revokes every legacy API key and signs every user out.
+ **Personal access tokens, not the API key.** Give each program or agent its own token with the scopes it needs
  (`php caligrafer.php token create`), let browser apps use the session (the JS client, or `apiHeaders()` for `Route::action` and controller
  routes, the session and `X-CSRF-Token` for the Vite SPA template since 2.19.1), then set `LEGACY_API_KEY=false`. The
  `API_KEY` is not a secret in the browser: Caligrafy gives it to the Vue apps it serves (`env.apiKey`, `null` with
  `LEGACY_API_KEY=false`).
+ **AI agents (MCP):** `Route::mcp()` accepts tokens only (a `POST /mcp` without one, session cookie or not, answers
  `401` with `WWW-Authenticate` and a JSON-RPC error, 2.19.1) and shows each agent the capabilities its scopes allow; mark
  capabilities that delete data `destructive: true`, and read `php caligrafer.php audit`.
+ **Administrators:** new users have `permissions` 0; promote administrators in the database.
+ **Queries:** the [query builder](https://github.com/caligrafy/caligrafy-quill/wiki/Queries) binds every value. Elsewhere
  use `?` placeholders (`Database::execute($sql, [$value])`, `all()` with `bindings`); never put request data in SQL.
+ **Uploads:** the `file` rule of a capability (`'cover' => 'required|file|extension,png;jpg|max_size,2mb'`), or
  `uploadFile($file, ['png', 'jpg'])`. Scripts, HTML and SVG files are always refused.
+ **Forms:** every `POST`, `PUT` and `DELETE` form prints `=csrf()`, `Route::form` and `Route::action` included. Never write
  data in a closure route: use `Route::form`, `Route::action` or a capability route.
+ **Web-only capabilities:** they may read the session, sign people in and change data on a `GET`, so only `Route::action`
  reaches them. A `GET` has no CSRF token: keep what it changes harmless, and use `'method' => 'POST'` and a form for the
  rest. After signing in on a redirect, give a new session id and CSRF token with `AuthRoutes::signIn($user)`; a page that
  stays open at least calls `session_regenerate_id(true)` before `Auth::authorize($user)`. Never trust `{id}` alone to say which row someone may open: check it against the person
  (`$context`).
+ **What a weak sign-in may do:** `AuthRoutes::signedInBy()` says how a session signed in (`password` and `passkey` through
  `Route::auth`; `AuthRoutes::signIn($user, null, 'face')` for your own). A face without a liveness check does not prove a
  person: refuse anything that changes how the account signs in unless it answers `password` or `passkey`.
+ **Sign-in:** `Route::auth` limits failed sign-ins and gives a new session id at sign-in. Behind a proxy every visitor
  has the proxy's address: the limit is then per username.
+ **Webhooks:** `Route::webhook` needs `verify`; with `'stripe'`, `STRIPE_WEBHOOK_SECRET` is the live endpoint's
  `whsec_...`. The capability refuses other callers and is safe to run twice.
+ **Jobs:** capabilities run by the queue, the scheduler or a webhook have full access: refuse other callers
  (`$context->actorType()`), and check who may ask before pushing a job.
+ **Example routes:** the OpenAI routes of the template call a paid API for anyone who reaches them: protect or remove
  them.
+ **Face login:** never sign in with a single face print; use `FaceLogin::verify()` and a passkey for sensitive accounts,
  with `PASSKEY_RP_ID` and `PASSKEY_ORIGIN` set ([face login](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition#face-login)).
+ **Database changes:** `php caligrafer.php migrate status` shows no `changed` migration; the deploy step runs the
  pending ones.
+ **Health check:** `php caligrafer.php doctor` (or `--env .env.production`): every configured service `OK`, Stripe in
  live mode.

## <a name="protections"></a>Reference: what the framework does for you

| Threat | Protection |
| - | - |
| Downloading `.env`, `.git` or source files | `.htaccess` denies dotfiles, `application`, `framework`, `vendor`, `tests`, `qa`, `docker`, `claude-plugin`, `archives`, `backups` (2.19.1), `node_modules`, `caligrafer.php`, `composer.*`, `docker-compose.yaml`, `package(-lock).json` and `.sql`/`.log`/`.bak`/`.ini`/`.sh`/`.env` files |
| Uploading and running a PHP file | `uploadFile()` and the `file` rule accept an allow-list of extensions; `public/uploads/.htaccess` denies scripts |
| SQL injection | The query builder, `find()`, `create()`, `update()`, `delete()`, `search()`, the relationships and `all()` with `bindings` bind every value; column and table names are checked |
| Cross-site request forgery | Forms must carry the session's `_token` (`=csrf()`); JSON writes with the session need `X-CSRF-Token` (`Route::form`, `Route::auth`, capability routes); every JSON call to `Route::action`, `GET` included, needs it or a token that grants `*` (2.21.1); webhooks have no session: their signature is checked instead |
| Guessing passwords, session fixation | `Route::auth` counts failed sign-ins per username and address (429 after 5 in 15 minutes), answers unknown usernames as slowly as known ones, and gives a new session id and CSRF token at sign-in and sign-out |
| A spreadsheet running a formula from a download | `Route::download` puts `'` before cells that start with `=`, `+`, `-` or `@` |
| Cross-site scripting through Vue apps | The `env` given to Vue apps is escaped: URL parameters cannot inject code |
| A script of the page reading the session | The session cookie is `HttpOnly`, and `Secure` on HTTPS (2.19.8). `env.request` of a Vue app is `request()->forClient()` (2.19.1): the method, host, address, route, its values and the query string; never the `Cookie` (the session id) or `Authorization` headers, nor a `POST` body |
| A query string replacing a route variable | `Route::page`, `Route::form`, `Route::action` and `Route::capability` keep the route variable: `/books/3?id=9` is the book 3 (2.21.2) |
| Open redirects after signing in | `/login?return=` follows a path of this site only; another site, `//...` or a backslash is ignored |
| A form choosing what only the server should | The `inputs` option of `Route::form` writes those values over anything the form sent |
| A browser-only capability reached by a program or an agent | `webOnly: true`: nothing but `Route::action` reaches it, and it is listed nowhere |
| Loading arbitrary files through client apps | `?app=` and the app folder accept letters, digits, `-` and `_` only, and only files of `public/<app>/` are served |
| A stolen password database | The authentication module stores `password_hash()` hashes |
| Signing in with a photo or a replayed face print | `FaceLogin` issues single-use liveness challenges and refuses identical or reused prints; `Passkey` (WebAuthn) checks a device signature bound to the domain |
| Choosing a secret through a form | The OpenAI example controller accepts only the documented commands and types |

## <a name="update-command"></a>Reference: `php caligrafer.php update`

```bash
php caligrafer.php update --check [<version>]   # what it would change
php caligrafer.php update [<version>] [--yes] [--no-composer]
```

1. `framework/` and `claude-plugin/` are replaced whole.
2. Every other file of the release (`caligrafer.php`, `.bin/`, `Dockerfile`, `index.php`, `public/css`, `public/js`...):
   an untouched copy is replaced, a missing one added, a changed one kept with the new version next to it as
   `<file>.caligrafy-new`. Your documents (`README.md`, `LICENSE`...) are left alone.
3. `composer.json` gets the new packages (then `composer update` for them) and, 2.22.1+, the release's `allow-plugins` the project did not change, `.gitignore` the new lines, `.env` the new
   settings with their defaults (existing values never change).
4. `php caligrafer.php upgrade --apply`, from the new release, brings `application/` up to date.

`application/`, the values of `.env`, `public/uploads` and `vendor/` are never replaced. `upgrade` checks for a newer
release too: when there is one, `upgrade` and `upgrade --apply` do what `update --check` and `update` do. Projects before
2.9.0 have no `update` command: see [Caligrafer: update](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#update).

## <a name="upgrade-command"></a>Reference: `php caligrafer.php upgrade`

```bash
php caligrafer.php upgrade            # dry run: prints the plan, changes nothing
php caligrafer.php upgrade --apply    # applies it
php caligrafer.php upgrade --local    # compares application/ with the templates of the release the project runs
php caligrafer.php upgrade --force application/views/Auth/login.pug          # replaces one customized file
php caligrafer.php upgrade --apply --keep application/views/default/index.pug   # keeps a default page that is now yours
```

Every file of `framework/settings/application` is reported as:

| Status | Meaning | With `--apply` |
| - | - | - |
| `missing` | new in the framework | copied into `application/` |
| `identical` | already up to date | nothing |
| `outdated` | an older template that you never changed | replaced |
| `kept` | an older template that you keep with `--keep` (remembered in the manifest) | **kept**; the new version is written next to it as `<file>.caligrafy-new` |
| `customized` | you changed it | **kept**; the new version is written next to it as `<file>.caligrafy-new` (or replace it with `--force`) |
| `held` | new files that would clash with how your project works (the user capabilities), the files that need them, and `AuthController` or `AdminController` in a project that signs in with `Route::auth` or whose routes no longer name them (2.19.3, 2.19.6, 2.19.7) | **not added**, with the reason; add one with `--force application/<path>` |
| `routes` | `config/routing/web.php` holds your routes | never replaced (except with `--force application/config/routing/web.php`) |

+ Every replaced file is first copied to `backups/caligrafy-upgrade-<YYYYmmdd-HHMMSS>/`. `.env`, `public/uploads`,
  `vendor` and the files you created in `application/` are never touched.
+ `initialize` and `upgrade --apply` write `application/.caligrafy-manifest.json` (the hash of each template as
  copied): commit it, it is how the next upgrade tells untouched files from yours. Projects without one are compared
  with the templates of the previous releases (`framework/settings/template-history.json`).
+ **Read the `outdated` list before `--apply`.** An untouched default page can be a page of your site: keep it with
  `--keep application/<path>`.
+ The settings of `framework/settings/.env.example` that your `.env` lacks are listed as `new`, obsolete ones as
  `obsolete` with what replaces them. Views and client apps that still use Bootstrap 3 classes are listed.
+ Client apps made with `php caligrafer.php app|bot|facedetect|ml` are listed with the files that differ from
  `framework/plugins/<type>`; they are never changed.
+ **Upgrading to 2.5.0** (the user capabilities): `upgrade --apply` adds `application/services/Users/` and replaces
  `AdminController` and `AuthController` when you never changed them. They are **held** when your `AdminController` is
  customized (set `CaligrafyUsers::ADMIN_LEVEL` to your level, then add the files with `--force`), or when
  `application/` already declares one of those capabilities or class names (rename yours first).
## <a name="changes"></a>Reference: behavior changes

| Area | Before | Now |
| - | - | - |
| `create()`, `update()`, `save()` | `0`, `''` and `false` were silently dropped | They are saved. Only `null` is skipped, and only the columns of the table are written (helper properties of a model are ignored) |
| `all()` | Raw clauses only | Raw clauses plus `bindings` for `?` placeholders |
| `search()` | Keywords inserted in the SQL | Keywords bound. Invalid column names throw an exception |
| `belongsToMany()` | Pivot creation failed with `INT UNSIGNED` ids or with a second pivot | Pivot columns copy the id type and constraint names are unique |
| `DB_PORT` | Ignored | Used, unless `DB_HOST` contains `;port=` |
| `session()`, `scripts()`, `keywords()`, `copyright()`, `metadata()` | Ignored `0`, `''` and `false` | Store them |
| `endWith()` | Only compared the last character | Compares the whole needle |
| `httpRequest()` | Only sent a body for `POST` | Sends it for every method except `GET` |
| `uploadFile()` | Accepted any extension | Allow-list (`DEFAULT_UPLOAD_EXTENSIONS` or your own list) |
| CSRF | An empty `APPROVED_AGENTS` approved requests without a User-Agent | Empty entries are ignored |
| `Payment::createCheckout()` | Crashed with a locale or a customer email | Works |
| `OpenAI` `COMPLETE` | Dropped the text after `[insert]` | Sends it |
| `GPT4OMINI`, `ASSISTANT_GPT4OMINI` | `gpt-4o mini` (invalid) | `gpt-4o-mini` |
| `Assistant::run()` | Always sent an empty model and no tools, disabling `file_search` | Only sends the overrides that are given |
| `Assistant::retrieveResponse()` | Could wait forever | Gives up after `$timeout` seconds (120) |
| `caligrafer initialize` | Generated new keys on every run | Keeps the keys of a signed project |
| Authentication | Reversible passcodes, any user could manage users | Hashed passwords (8 to 72 characters), administrators need `permissions >= 1` |
| `APP_DEBUG=false` | Still turned the SMTP debug output on (`.env` values are strings) | Parsed as a boolean |
| Bot app | Loaded the latest Vue from a CDN | Pinned Vue 2.7.16; since the library upgrade, a Vue 3 chat on `scripts('vue')` (Vue 3.5.44) |
| Error responses | HTTP `200` for every error, including PHP fatal errors, with `[ERROR ...]` text | Real status codes: `401` (1004, access denied: since 2.7.0 the message ends with the reason), `403` (3000, CSRF), `404` (1001, controller or action), `405` (1000: the address answers other methods, with an `Allow` header, 2.16.0), `500` (other errors; for PHP fatal errors and uncaught exceptions the message is only shown with `APP_DEBUG=true`). API calls get `{"error": {"code": ..., "message": ...}}`. **Clients that expected `200` on errors must check the status** (axios and `fetch().ok` now treat them as failures) |
| Controller names | The example controllers of `application/controllers/core/` were global classes: a controller of yours named `AIController`, `AdminController`, `AuthController`, `ClientController` or `WatsonController` was a fatal error (`Cannot redeclare class`) on every page | They are in `Caligrafy\Controllers`. Routes accept fully qualified controllers (`'Shop\OrderController@show'`, leading `\` allowed); a short name that is not a declared class falls back to `Caligrafy\Controllers`, so old routes keep working and your own class of the same name wins. If your code referenced an example class directly (`new AuthController()`, `extends AIController`), use `Caligrafy\Controllers\...` |
| Relationships with namespaced models | The default foreign key of `hasOne`, `hasMany`, `belongsToMany` included the namespace | Uses the short class name (`Shop\Order` gives `order_id`) |
| Client apps (`?app=`) | Any path, including sub-folders and `../` | A file name of `public/<app>/` only (letters, digits, `-`, `_`): no sub-folders, no symbolic links pointing outside the app |
| Pug views (2.17.0) | Compiled on every request | Compiled once and kept in a private folder of the temporary directory, again when a view or a file it includes changes (`VIEW_CACHE=false` turns it off) |
| Classes of `application/` (2.18.0) | Every PHP file loaded on the first unknown class of each request | Each class loaded when first used, from a class map; a file with functions or top-level code is still loaded at start (`CLASS_MAP=false` restores the old way) |
| `tests/` (2.18.0) | Every PHP file loaded on each request | Your app's PHPUnit tests (`php caligrafer.php test`), never loaded on a page |
| Capabilities (2.18.0) | Built with `new` | Built by the container: their constructors get what they ask for (`application/config/container.php`) |
| Sessions (2.19.0) | Started on every request | Started when used. A request with a session cookie, and every `POST`, `PUT` and `DELETE`, starts it as before. A `GET` or `HEAD` without one (a first visit, an API client, an agent) gets a session only when it reads the CSRF token (`session('token')`, `csrf()`), writes the session after `config.php`, or prints a page that carries the token. Code that reads `$_SESSION['token']` directly on such a request should call `session('token')`. `SESSION_LAZY=false` starts every session, as before |
| Pug debug mode (2.19.0) | Always on | Only with `APP_DEBUG=true` (Pug line numbers in errors); cached views run through Phug's Optimizer (`VIEW_OPTIMIZER=false` turns it off) |
| Output buffer (2.19.0) | 1 MB reserved for every request | Grows with the page; errors still get their status code |
| Database rows (2.19.0) | Encoded to JSON and back (a row with invalid UTF-8 became `null`) | Fetched as arrays: the same arrays, faster, and such a row is kept |
| `Model::find()` (2.19.0) | A declared method | Provided through `__call()` (`$book->find(1)`, as before) and `__callStatic()` (`Book::find(1)`, the query builder). A model that declares its own `find()` keeps it for instances, but `Book::find()` then fails: use `Book::query()->find(1)`. `method_exists($model, 'find')` is now `false` |
| `.env` (2.19.0) | Parsed on every request | Read from `.env.php` when the deploy step or `php caligrafer.php env cache` compiled it and `.env` has not changed since (`env clear` removes it) |
| `Auth::logout()`, `terminateSession()` (2.19.0) | Always touched the session | Only when one is active |
## <a name="libraries"></a>Reference: upgrading to the current libraries (October 2026)

This release moves Caligrafy to current versions of every library and service. As with the security fixes, **new projects get everything automatically**; existing projects follow the steps below. The [Release notes: October 2026](https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-October-2026) give the same steps as a checklist, with every other change of October 2026.

**1. Requirements:** PHP 8.3 or higher (the Docker image uses PHP 8.5), MySQL 8.4, Node.js 20.19+ or 22.12+ for the Vue SPA template. Run `composer update` after pulling the framework.

**2. `.env`:** add the new settings when you use the matching module (see `framework/settings/.env.example`):

| Setting | Module |
| - | - |
| `COINBASE_API_KEY_NAME`, `COINBASE_API_KEY_SECRET` (replace `CRYPTO_PAY_KEY`) | Crypto payments (Coinbase Business) |
| `WATSON_URL` (required), `WATSON_ENVIRONMENT_ID`, `WATSON_API_VERSION` | Watson bots |
| `OPEN_AI_MODEL`, `OPEN_AI_IMAGE_MODEL` (optional) | OpenAI and Assistants |
| `GROQ_MODEL`, `GROQ_VISION_MODEL` (optional) | Groq agents |
| `PWA_SERVICE_WORKER` (optional, `false` by default) | Offline page of installed apps ([Views](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#install)) |
| `PASSKEY_RP_ID`, `PASSKEY_ORIGIN` (in production; not in `.env.example`, the request host is used without them) | Passkeys ([details](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.2-Face-Detection-and-Face-Recognition#passkeys)) |
| `AGENT_PROVIDER`, `TOGETHER_API_KEY`, `FIREWORKS_API_KEY`, `OPENROUTER_API_KEY`, `AGENT_API_KEY`, `AGENT_API_BASE`, `AGENT_MODEL`, `AGENT_VISION_MODEL` (optional) | Open source agents on another provider than Groq ([details](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.6-Open-Source-Agents-(llama,-Mistral-etc.))) |

**3. Views (Bootstrap 5):** the layout now loads Bootstrap 5.3 instead of Bootstrap 3.3.7, and no jQuery. Copy the new views of `framework/settings/application/views` (at least `default/master/layoutblocks.pug`, `default/modules/messaging.pug`, `default/modules/cryptopayment.pug`, `default/pages/payment.pug`, `default/pages/checkout.pug` and the `Auth` views) and delete `default/modules/gestures.pug`. Replace `default/modules/install.pug` (add-to-homescreen) with the new one and add `default/modules/serviceworker.pug` (`php caligrafer.php upgrade --apply` does both when you never changed them). If you customized `layoutblocks.pug`, add `meta(name='theme-color', content='#ffffff')` and `link(rel='manifest', href="{$home}public/manifest.webmanifest")` to the headers, and `include ../modules/serviceworker` then `if $install` / `include ../modules/install` after `include ../modules/standalone` (see [install to home screen](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#install)). If you customized the root `.htaccess`, copy its `Service-Worker-Allowed` lines and the `AddType application/manifest+json .webmanifest` block. Update `public/css/theme.css` too: its end keeps the Caligrafy black and white look on Bootstrap 5 (14px text, cards, black `btn-primary`, white `btn-secondary` with black text, black focus rings, readable `a.btn` links). It also keeps the Bootstrap 3 layout: full-width page container, header title centered in the header, grids centered in their wrapper, Caligrafy card borders and colors, Bootstrap 3 text color and button metrics. If you customized `theme.css`, copy everything from the "Bootstrap 5 compatibility layer" comment to the end of the file. Its heading margins apply to `body.caligrafy-layout` (and `body#gesturize`, so older copies of `default/master/layout.pug` keep their look): add `class='caligrafy-layout'` to the body of your own layouts. Client apps that reuse the Caligrafy header can replace a custom `margin: 20px 0 10px` on the header title with the class `caligrafy-header` on the header. In your own views, wrap Bootstrap columns in a `.row` and move them one breakpoint up (`col-sm-6` becomes `col-md-6`, `col-md-4` becomes `col-lg-4`, see [Views](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views)). Single page apps created before October 2026 load Bootstrap 3 and jQuery from their `index.html`: replace those three tags with `https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css` and `https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js` and update the columns of their components the same way. To keep Bootstrap 3 in a project for now, add to `application/config/config.php`:
```php
scripts('bootstrap_css', 'https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/css/bootstrap.min.css');
scripts('bootstrap_script', 'https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/js/bootstrap.min.js');
scripts('bootstrap_jquery', 'https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js');
```

**4. Client apps in `public/`:** apps created with Caligrafer are copies. Update their markup to `scripts('vue')` and `scripts('axios')` (pinned versions), and re-create or compare the bot, FaceDetect and ML apps with `framework/plugins`. The shared services (`public/js/services/detect.js`, `mlcore.js`, `face-api.min.js`, `stripe_client.js`, `passkey.js`) and the models in `public/resources/models` are updated with the framework.

**5. Code that calls the changed APIs:** see the table below.

| Area | Before | Now |
| - | - | - |
| PHP | 7.2+ | 8.3+; deprecation notices are never printed into pages |
| Composer | `dev-master` branches | Stable releases: stripe-php 22, Phug 2, Pug-php 3.6, PHPMailer 7, phpdotenv 5.8, GUMP 2.3, SimpleImage 4.4, groq-php 1.4, lbuchs/webauthn 2.2 (passkeys); PHPUnit 12 for the unit tests (development) |
| Bootstrap / jQuery | Bootstrap 3.3.7 + jQuery 1.12 | Bootstrap 5.3.8, no jQuery (jQuery 4 only for Summernote) |
| Add to home screen | add-to-homescreen.js 3.2.3 (`$install`, `add_to_home` scripts keys) | Web app manifest `public/manifest.webmanifest` linked by the layout, `'install' => true` shows an Install button (`beforeinstallprompt`) or the iOS Share hint, optional offline service worker `PWA_SERVICE_WORKER=true` ([Views](https://github.com/caligrafy/caligrafy-quill/wiki/7.-Views#install)) |
| Hammer.js gestures | Included in the layout | Removed |
| OpenAI text | `gpt-3.5-turbo` (shut down) with temperature/max_tokens defaults | `gpt-6-luna`, only the model is sent by default |
| OpenAI images | DALL.E (shut down), URLs | `gpt-image-2`, base64 in `b64_json` |
| `Assistant` | Assistants API (shut down Aug 26, 2026) | Responses + Conversations APIs, same methods, vector stores for files ([details](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.5-Open-AI:-Assistants#migrating)) |
| Stripe Checkout | `sessionId` + `redirectToCheckout` (removed) | Redirect to `$result['url']` |
| Stripe card form | Card Element | Payment Element (`stripe.confirmPayment`) |
| `createCheckout()` | `payment_method_types` = `['card']` | Payment methods from the Stripe dashboard (current API versions reject the parameter) |
| `CryptoPayment` | Coinbase Commerce (shut down Mar 31, 2026) | Coinbase Business Checkouts with CDP keys; `$transaction['url']` |
| Groq `Agent` | Llama 3.x defaults (retired), Groq only | `openai/gpt-oss-120b`, `qwen/qwen3.8-27b` (vision), `whisper-large-v3`; `AGENT_PROVIDER` selects Together AI, Fireworks AI, OpenRouter (Llama), Ollama (local Llama) or a custom endpoint; `configure()` parameters are now sent ([migrating from the Groq Llama models](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.6-Open-Source-Agents-(llama,-Mistral-etc.)#migrating)) |
| Watson | URL of a fixed instance, version 2021-11-27 | `WATSON_URL`, optional environment, version 2024-08-25 |
| Bot client | BotUI + Vue 2 | Vue 3 chat; `pause` actions call `window.executeBotAction(context)` |
| FaceDetect | face-api.js 0.22 (abandoned) | @vladmandic/face-api 1.7.15; MTCNN removed; `detector.ready` promise; `{ autoStart: false }` + `startStream()` (rejects with camera errors, `streamError`), `stopStream()`, `faceprint()` |
| ML Core | ml5 0.12 (poseNet, uNet) + p5 0.9 | ml5 1.4 (bodyPose, bodySegmentation) + p5 2.3; callbacks receive `(results, error)`; the previous pose shape is kept |
| Vue SPA template | Vite 7, Vuex, ESLint 9 legacy config | Vite 8, Vue Router 5, Pinia, ESLint 10 flat config |
| Docker | php:8.2.2, mysql:latest, phpmyadmin:latest | php:8.5-apache, mysql:8.4, phpmyadmin:5.2.3 |
## <a name="qa"></a>Testing the framework

> Contributors: [Testing Caligrafy](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Caligrafy) explains every phase of the QA suite, the unit tests, how to add a test and the release process.

Caligrafy comes with a QA suite that runs the framework, HTTP and tooling tests in an isolated Docker stack (the first free ports from 8090 and 3316, so it never clashes with your development servers). From a clean checkout of the framework:
```bash
composer install
./qa/run.sh
```
The suite refuses to run when an `application` folder or a `.env` file that it did not create is present. Its stack includes stripe-mock, and the OpenAI, Coinbase, Groq and Watson integrations are tested against local mock servers, so no API key is needed.

If the Docker image cannot be built on your network (see the Docker troubleshooting below), build or obtain the `quillqa-web` image once and run the suite with `QA_NO_BUILD=1 ./qa/run.sh`: it reuses the existing image instead of rebuilding it.

The suite also runs the PHPUnit unit tests of the framework core (`qa/unit`: routing, errors, requests, models, validation, upgrade and doctor helpers, face login checks and passkeys, capabilities, tokens, deploy, the scheduler, the view cache, the class map, migrations, the container, the cache, the query builder, lazy sessions and the declarative routes). They need no web server, database or `.env`, so you can run them on their own with the development dependencies installed:
```bash
composer install
vendor/bin/phpunit
```

**`.env` comments:** write comments on their own line (`# ...`). Some tools and the QA suite read `.env` with PHP's `parse_ini_file`, which fails on text after `true`/`false` (`FLAG=false # comment`) and on parentheses in unquoted values; the QA tooling phase checks the templates.

**Docker image build killed during `apt-get` on slow or proxied networks:** on some corporate networks `apt-get install` in `docker/Dockerfile` grows to several GB while it retries slow downloads and the build fails with "Killed" / "cannot allocate memory". Give Docker Desktop more memory (Settings, Resources), close other containers and retry, or build on another network; for the QA suite, reuse an existing image with `QA_NO_BUILD=1`.
## Other ways

### The manual upgrade

Without `update` (a project you cannot run it in), the steps it does by hand:

**1. Update the framework**
```bash
git pull   # or: composer update / download the new release
```

**2. Copy the root and uploads `.htaccess` files** from the new release (keep your own additions). Then check that `.env` is no longer served: `curl -I http://<your-host>/.env`.

**3. Update the files of your `application` folder** that you have not customized, from `framework/settings/application` (`php caligrafer.php upgrade` does this step for you):

| File | Why |
| - | - |
| `views/Client/app.pug` | Path traversal through `?app=` and script injection through URL parameters (**required** if you use Vue, bot, FaceDetect or ML apps) |
| `controllers/core/AI/ClientController.php` | Validates the `?app=` parameter |
| `controllers/core/AI/AIController.php` | The previous version let a form select any PHP constant, including your `.env` secrets (**required** if the `/ai` routes are enabled) |
| `controllers/core/Auth/AuthController.php` and `AdminController.php` | Password hashing, exact username lookup (the previous login accepted `%` as a username), admin pages restricted to `permissions >= 1` |
| `models/Auth/User.php` | `findByUsername()`, `hashPassword()`, `verifyPassword()`, `needsRehash()` used by the controllers above |
| `views/Auth/login.pug`, `register.pug`, `manageusers.pug` | Passwords of up to 72 characters |
| `models/Auth/create_db.sql` | No longer drops the `users` table |
| `controllers/core/AI/*.php`, `controllers/core/Auth/*.php` | The example controllers are declared in the `Caligrafy\Controllers` namespace, so a controller of yours with the same name (`AIController`...) no longer collides with them. Your routes do not need to change: short names such as `'ClientController'` fall back to `Caligrafy\Controllers` |
| `config/routing/web.php` | The `catch` at the end calls `Errors::handle($e);` instead of `echo $e->getMessage();` (add `use Caligrafy\Errors;`), so API clients get JSON errors. Without this change the framework errors (401, 403, 404) still get their status code, but other exceptions (database errors, your own) still answer `200`, and every body stays plain text |

If you customized these files, apply the same changes to your versions: compare them with the new files of `framework/settings/application`.

**4. Upgrade the `users` table** (authentication module):
```sql
ALTER TABLE users MODIFY passcode varchar(255) NOT NULL;
```
Since 2.18.0, put such a change in a [migration](https://github.com/caligrafy/caligrafy-quill/wiki/Migrations) (`php caligrafer.php migrate make users_passcode_255`) so that every server gets it.
Existing users keep logging in with their passwords: their passcode is converted to a hash on their next login. Keep the same `APP_KEY` until they have all logged in once.

**5. Promote your administrators**: `UPDATE users SET permissions = 1 WHERE username = '...';`

**6. Review the [behavior changes](#changes)** in your own code.
## Common mistakes

+ **Pages are slow online.** `APP_DEBUG=true`: Phug's debug mode makes every page about three times slower.
+ **A setting changed on your own server is ignored.** It is not: an edited `.env` is read as it is until the next
  `php caligrafer.php env cache`. A value that still looks old comes from a `.env.php` compiled from another `.env`:
  run `env cache` again, or `env clear`.
+ **`.env.php` in git.** It holds every secret of `.env`: remove it from git, change the keys, and keep the
  `.gitignore` line.
+ **A form answers `[ERROR 3000]` after the update to 2.19.** Its page does not print `=csrf()`, or code reads
  `$_SESSION['token']` before the session started: use `session('token')`. `SESSION_LAZY=false` brings the old sessions
  back while you fix it.
+ **`update` piped into `tail`.** The pipe hides its exit code and its last lines (`upgrade --apply`): run it whole.
+ **`.caligrafy-new` files committed.** Merge them into your files and delete them before committing.
+ **`backups/` online.** It can hold views and SQL scripts. Before 2.19.1 the root `.htaccess` did not refuse it: take
  the 2.19.1 `.htaccess` (`backups` in its folder rule), delete the folder, or keep it out of the server (the
  production image leaves it out).
## Related pages

+ [Putting it online](https://github.com/caligrafy/caligrafy-quill/wiki/Putting-it-Online)
+ [Caligrafer](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer)
+ [Authentication](https://github.com/caligrafy/caligrafy-quill/wiki/9.1-Authentication)
+ [Release notes: 2.19.0](https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.19.0)
+ [Testing Caligrafy](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Caligrafy)

<br /><br />
>[Next Section: Learn about the Claude Code Plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Caligrafy -->

This page is for contributors to Caligrafy Quill: how the framework is tested, how to run all or part of the tests, how to add a test, and how a release is prepared. You do not need any of it to build an application with Caligrafy. How the framework itself is built (the request lifecycle, capabilities, the `Context`, the design decisions) is in [ARCHITECTURE.md](https://github.com/caligrafy/caligrafy-quill/blob/master/ARCHITECTURE.md).

Run every command from the root of a **clean checkout of the framework** (`git clone https://github.com/caligrafy/caligrafy-quill.git`), not from one of your projects.
## <a name="overview"></a>Two kinds of tests

| | Unit tests | QA suite |
| - | - | - |
| Where | `qa/unit` | `qa/run.sh`, `qa/tests`, `qa/fixtures` |
| What | The core classes, one at a time | The whole framework: database, HTTP requests through Apache, Caligrafer, client apps, the Claude plugin |
| Needs | PHP 8.3+ and `composer install` | Docker, PHP with curl on the host, Node.js and `composer install` |
| Time | A few seconds (333 tests) | Several minutes (the first run builds a Docker image) |
| Command | `vendor/bin/phpunit` | `./qa/run.sh` |

Run the unit tests while you work, and the QA suite before you open a pull request. When you change `framework/` or `framework/settings/application`, add a test for the change.
## <a name="qa"></a>The QA suite

```bash
composer install
./qa/run.sh            # builds the stack, runs every phase, removes everything
./qa/run.sh --keep     # leaves the stack and the generated files in place, for debugging
```

`qa/run.sh` starts its own Docker stack (`qa/docker-compose.yml`, compose project `quillqa`): the web server built from `docker/Dockerfile` (stage `dev-php`, with the checkout mounted into it) on the first free port from `8090`, MySQL 8.4 on the first free port from `3316`, and Stripe's official mock (`stripe/stripe-mock`). The ports never clash with your development server (`8080`, `3306`); set them with `QA_WEB_PORT` and `QA_DB_PORT`. No API key is needed: OpenAI, Groq and the other Agent providers, Coinbase, Watson and SMTP are replaced by small mock servers from `qa/fixtures`.

Before the phases, it generates what a project needs and removes it at the end: a `.env` from `framework/settings/.env.example` (marked `# QA-GENERATED`, with `DB_HOST=mysql` and the database `quillqa`), an `application` folder copied from the templates (marked with `application/.qa-generated`) plus the fixtures of `qa/fixtures/application` and `qa/fixtures/facelogin`, the QA routes added to `web.php` (with every commented route of the template turned on, and the 2.19 declarative routes), the client apps `public/qaapp`, `public/qabot`, `public/qafacedetect` and `public/qafacelogin`, and the tables of `models/Auth/create_db.sql`, `qa/fixtures/books.sql`, the face login fixture and `platform install`. Inside the web container it also serves the Watson mock (port `8769`) and the push service mock (port `8770`).

> **The suite refuses to run** when an `application` folder or a `.env` file that it did not create is present: move them aside or use a clean checkout. Note that every Caligrafer command except `version` and `doctor` creates `.env` from the template when it is missing: delete that copy before you run the suite.

### Phases

| Phase | Runs | Covers |
| - | - | - |
| Database scripts | `mysql` in the `mysql` container | `models/Auth/create_db.sql` can be run again without deleting users; `platform install` can be run again |
| Framework tests | `qa/tests/cli_tests.php` in the web container | Models (CRUD with falsy values, SQL injection, relationships and pivots), validation, the database connection, helpers, OpenAI request building, the Assistant on the Responses and Conversations APIs, Stripe against stripe-mock, Coinbase Business with real JWT signatures, the Groq Agent and the other Agent providers, Watson |
| Unit tests | `vendor/bin/phpunit --colors=never --do-not-cache-result` in the web container | The PHPUnit tests of `qa/unit` (see [below](#unit)) |
| HTTP tests | `qa/tests/http_tests.php` on the host, against `http://localhost:8090` (or the next free port) | The front controller, the web app manifest and service worker, server files that must not be served, client apps (`?app=`), CSRF and API access, the REST API example of the wiki, uploads, the authentication module, the AI controller, face login with liveness and passkeys, the [declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes) (2.19.0: `Route::auth`, `Route::form`, file inputs, `Route::webhook`, `Route::download`; 2.19.1: the `POST /logout` form), MCP without a token (`401`, 2.19.1), `backups/` denied (2.19.1), HTTP status codes |
| Doctor tests | `qa/tests/doctor_tests.sh` | `php caligrafer.php doctor` against the mocks: good and wrong keys, unknown models, leading spaces, DNS errors, Agent providers, masked secrets |
| FileInfo hosts | `qa/run.sh` itself | The `.htaccess` rules on a host that only allows `AllowOverride FileInfo`: pages still load, server files and uploaded scripts answer `403`, `sw.js` keeps `Service-Worker-Allowed` and the manifest its type |
| Tooling tests | `qa/tests/tooling_tests.sh` on the host | `php -l` on the framework, `caligrafer initialize` and `upgrade` on an older project, the client app scaffolds, the liveness logic (`node qa/tests/liveness_tests.js`), front-end libraries (pinned and reachable CDN URLs, no jQuery, no Bootstrap 3), the Bootstrap 5 compatibility layer of `theme.css`, `.env` templates, the web app manifest, the Vue SPA template (build, ESLint, `npm audit`; since 2.19.1 relative paths, hash history, no API key in the bundle, `dist/` kept in git), the project's `.gitignore` (every `.env.*` but `.env.example`) and `migrate --env <file>` (2.19.1), the Claude plugin |

The suite exits with `0` when every phase passes. Each check prints `PASS` or `FAIL` with the reason.

### Running part of the suite

| To run | Command |
| - | - |
| The unit tests only | `vendor/bin/phpunit` (no Docker) |
| The tooling tests only | `sh qa/tests/tooling_tests.sh` (no Docker; add `QA_SKIP_SPA=1` to skip the Vue SPA build, which needs npm and the network). It ends with `<n> passed, <n> failed` |
| The liveness and passkey client tests | `node qa/tests/liveness_tests.js` |
| A phase that needs the stack | `./qa/run.sh --keep` once, then for example `docker compose -f qa/docker-compose.yml exec -T web php qa/tests/cli_tests.php` or `php qa/tests/http_tests.php`; clean up with `docker compose -f qa/docker-compose.yml down -v` and remove the generated files |

### Options

| Variable | Effect |
| - | - |
| `QA_WIKI=<wiki clone>` | The tooling phase also checks that the wiki mirrors of the Claude plugin are up to date with that clone (`sync-wiki.py --check`). Without it, the check is skipped |
| `QA_NO_BUILD=1` | Reuses the existing `quillqa-web` image instead of rebuilding it. Use it on networks where the image build fails |
| `QA_SKIP_SPA=1` | Skips the Vue SPA build of the tooling phase |
| `QA_WEB_PORT`, `QA_DB_PORT` | Ports of the stack (default: the first free ports from `8090` and `3316`) |

The tooling phase runs `claude plugin validate` only when the `claude` command is installed, and then also checks that Claude Code runs the plugin version of the checkout.

For example, before a release:
```bash
git clone https://github.com/caligrafy/caligrafy-quill.wiki.git ../caligrafy-quill.wiki
QA_WIKI=../caligrafy-quill.wiki ./qa/run.sh
```

### One stack at a time

The stack always has the same compose project name (`quillqa`) and ports, and the suite writes `.env`, `application` and the `public/qa*` apps into the checkout. Two runs at the same time, even from two checkouts, share the same containers: one run tears down the stack of the other. Check that no QA stack is running before you start one:
```bash
docker ps --filter name=quillqa
```

### When the image cannot be built

On some slow or proxied networks, `apt-get install` in `docker/Dockerfile` grows to several GB while it retries and the build is killed ("Killed", "cannot allocate memory"). Give Docker more memory, close other containers, or build on another network. Once a `quillqa-web` image exists, run the suite with `QA_NO_BUILD=1 ./qa/run.sh`.
### <a name="buildonce"></a>Build once: the cross-channel tests
The HTTP phase proves that one capability behaves the same on every channel, with the Bookshelf capabilities of `qa/fixtures/application/services/Books`: a book created on a web page (`BookPageController`, `Controller::call()`) is the same through REST (`Route::capability`), the generic endpoint, MCP over HTTP and stdio, and the generated JS client run in Node; invalid input gets the same field errors everywhere; a token without the scope, or an owner without the level, is refused on REST and MCP alike; and the audit log names each channel. Tokens are created with `php caligrafer.php token create` inside the web container, like a user would.

## <a name="unit"></a>Unit tests (PHPUnit)

```bash
composer install                               # installs PHPUnit 12 (require-dev)
vendor/bin/phpunit                             # every test of qa/unit
vendor/bin/phpunit qa/unit/RouteTest.php       # one file
vendor/bin/phpunit --filter testBase64Url      # one test
```

The configuration is `phpunit.xml.dist`: test suite `unit` (the folder `qa/unit`), bootstrap `qa/unit/bootstrap.php`, and warnings or risky tests make the run fail.

### What each test file covers

| File | Covers |
| - | - |
| `RouteTest.php` | `Route::resolveController()`: a global class wins over the example namespace, namespaced controllers with or without a leading backslash, short names that fall back to `Caligrafy\Controllers`, unknown controllers |
| `ErrorsTest.php` | `Errors::status()` (404, 401, 403, 500), `Errors::raise()`, the JSON error body for API requests and the plain text for HTML requests |
| `RequestTest.php` | `Request::wantsJson()`, the API key check (`authorizeApiRequest()`) with valid, invalid and missing keys, the session check (`authorizeSessionRequest()`, the `X-CSRF-Token` header) and the reason of a refusal (`apiRefusal()`); `forClient()`, the `env.request` of client apps without the `Cookie`, the `Authorization` header or a `POST` body (2.19.1) |
| `ModelTest.php` | `prepareInputs()` keeps `0`, `''` and `false` and drops `null` and restricted properties; identifier quoting accepts safe names and rejects unsafe ones |
| `ControllerTest.php` | `validate()` and `filter()` (GUMP) |
| `UpgraderTest.php` | `caligrafer upgrade` in a temporary project: the classification of files, the template history, `--apply` only replaces untouched files and never touches `.env` |
| `DoctorTest.php` | `Doctor::mask()` and the key format checks (leading space, missing dash after the prefix) |
| `DoctorWebAppTest.php` | The install to home screen check of doctor: the framework manifest, missing or invalid manifests, missing icons, required sizes and fields, the service worker check only when `PWA_SERVICE_WORKER` is on |
| `AgentTest.php` | `Agent::settings()`: Groq is the default, the `GROQ_*` and `AGENT_*` settings, key precedence, the defaults of every provider, Ollama without a key, unknown providers |
| `FaceLoginTest.php` | `FaceLogin`: random challenges kept in the session, a nonce accepted once (even when the check fails), expiry, wrong nonce or account, challenge order, identical prints, prints of different faces, print format and count, account matching, print hashes |
| `PasskeyTest.php` | `Passkey` against a software authenticator: registration options, register and authenticate, excluded credentials, replayed assertions, single-use challenges, wrong origin, bad signature, sign counter going back, another user's passkey, user verification, relying party |
| `CapabilitiesTest.php` | The registry of capabilities: attributes, checks of scope and level, validation, the audit, `Capabilities::call()` |
| `ContextTest.php` | `Context`: the CLI, guests, users, tokens and system contexts, scopes and levels |
| `TokensTest.php` | Personal access tokens: format, hashing, scopes, expiry, revocation |
| `ClientTest.php`, `McpServerTest.php` | The generated JS client, and the MCP server (tools listed by scope, calls and errors; a `POST` without a token gets the JSON-RPC `401`, not the CSRF error, 2.19.1) |
| `DeployerTest.php` | `php caligrafer.php deploy`: which `create_db.sql` scripts run, the destructive ones never twice |
| `SchedulerTest.php` | Scheduled jobs: the declaration of `schedule.php`, cron, the listing Caligrafy Cloud reads |
| `NotifyTest.php` | Notifications without a database: message rules, channels, keys, the signed unsubscribe link |
| `CloudClientTest.php`, `UpdaterTest.php`, `QuickstartTest.php`, `PluginSourceTest.php`, `VersionTest.php`, `DesignsTest.php` | The `cloud`, `update`, `quickstart`, `plugin`, `version` and `design` commands |
| `DoctorFormsTest.php`, `DoctorPugTest.php` | Doctor's checks of forms without a method and of two Pug mistakes |
| `ViewTest.php` | The compiled view cache (2.17.0): a private folder, an edited view compiled again |
| `ClassMapTest.php` | The class map (2.18.0): declarations found, classes loaded when used, files that run at start, a new class found at once |
| `MigrationsTest.php` | Migrations (2.18.0): how a script is split, the order and names of the files, `make` |
| `ContainerTest.php` | The container (2.18.0): constructor injection, bindings, singletons, instances, clear errors |
| `CacheTest.php` | The cache (2.18.0): the default store, JSON values, expiry, `remember`, `off` |
| `ValidatorRulesTest.php` | The `exists`, `unique` and `current_year` rules (2.19.0): the ignored row of `unique`, names checked like the query builder, the app's own message, their use in services, a schema rule without its argument |
| `TestCaseTest.php` | `Caligrafy\Testing\TestCase`: each test starts without the queries of earlier tests (no N+1 warning carried over) |
| `QueryTest.php`, `QueryModelTest.php`, `QueryEagerTest.php`, `DatabaseQueryTest.php` | [Queries](https://github.com/caligrafy/caligrafy-quill/wiki/Queries) (2.19.0): the SQL and bindings of the query builder, validated names, writes without a `where`, `Book::query()` and the model forms, eager loading (`with`, `withCount`, pivots), and on an in-memory SQLite the transactions and the N+1 warning. `php qa/bench-query.php` (not part of the run) times 10,000 queries |
| `SessionLazyTest.php` | Sessions only when used (2.19.0): what starts a session, and when a request without a session cookie saves one |
| `FormRouteTest.php`, `UploadsTest.php`, `AuthRoutesTest.php`, `WebhookTest.php`, `DownloadTest.php` | The [declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes) (2.19.0): `Route::form` (redirects, errors, old input, flash), the `file` rule (`required_file` and `required\|file` refuse a missing file, 2.19.1), `Route::auth` (sign-in, lock, session regeneration, the `POST /logout` form, 2.19.1), `Route::webhook` (signatures), `Route::download` (CSV, file names) |

### How the bootstrap loads the framework

The unit tests run without a web server, a database or a `.env`. `qa/unit/bootstrap.php` does only what the tested classes need:

1. defines a test `APP_KEY` (constant and environment variable),
2. requires `vendor/autoload.php` and `framework/helpers/corehelpers.php`,
3. requires the core classes and interfaces under test one by one (the list is in `qa/unit/bootstrap.php`: `Errors`, `Route`, `Request`, `Model`... `ClassMap`, `View`, `Migrations`, `Container`, `Cache`, `Query`, `Form`, `Uploads`, `AuthRoutes`, `Webhook`, `Download`..., `Rest`, `Mcp/Server`, `Mcp/Http`, `Client` and `framework/database/Database.php`, with `DB_ACTIVATE=false`: the query tests give `Database::useConnection()` an in-memory SQLite),
4. requires the fixtures of `qa/unit/fixtures`: test controllers in the global, `Shop` and `Caligrafy\Controllers` namespaces, `QaSoftAuthenticator`, a software WebAuthn authenticator (EC P-256, "none" attestation) also used by the HTTP tests, the test capabilities of `services.php`, and `query.php` (an executor that records the queries of the query builder, and test models).

It never calls `Framework::init()`: no route is dispatched. Classes whose constructor needs the live request or the database are built without their constructor (`ReflectionClass::newInstanceWithoutConstructor()`), and the tests set the properties they need. `Passkey` keeps its credentials in memory by overriding its 4 storage methods. Tests that need files (`UpgraderTest`, `DoctorWebAppTest`) create a temporary project and delete it in `tearDown()`.

### Why `qa/unit` and not `tests/`

`tests/` belongs to the applications: since 2.18.0 it holds an app's own tests (`php caligrafer.php test`, [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App)), and projects keep it when they update. The framework's unit tests therefore live in `qa/unit`, which the framework never loads (and which `.htaccess` denies to browsers). Before 2.18.0 the framework also loaded every PHP file of `tests/` on every request.

### Adding a unit test

1. Create `qa/unit/<Something>Test.php` with a `final class <Something>Test extends TestCase` (`use PHPUnit\Framework\TestCase;`) and `public function test...(): void` methods.
2. If the class under test is not loaded yet, add it to the list of `qa/unit/bootstrap.php`.
3. Keep it independent of the network, the database and `.env`: build objects without their constructor when it reads the request or connects, restore every superglobal (`$_SERVER`, `$_SESSION`) and setting you change in `tearDown()`.
4. Run `vendor/bin/phpunit`.

```php
<?php

use Caligrafy\Errors;
use PHPUnit\Framework\TestCase;

final class ErrorsExampleTest extends TestCase
{
    public function testCsrfErrorIsForbidden(): void
    {
        $this->assertSame(403, Errors::status(3000));
    }
}
```
## <a name="fixtures"></a>Mocks and fixtures (`qa/fixtures`)

| Fixture | Used for |
| - | - |
| `openai_mock.php` | OpenAI Responses, Conversations, Files, Vector Stores and models endpoints (Assistant, doctor). Every request is logged to `qa_openai_mock.log` in the temporary folder, so a test can check what was sent |
| `groq_mock.php` | The OpenAI-compatible endpoints of `Agent` and doctor. The first path segment picks the provider: `/openai/v1` (Groq), `/together/v1`, `/fireworks/inference/v1`, `/openrouter/api/v1`, `/ollama/v1`, `/ollama-empty/v1` (no model pulled), `/custom/v1` |
| `coinbase_mock.php` | Coinbase Business Checkouts API. It logs each request with its `Authorization` header to `qa_coinbase_mock.log`, and `cli_tests.php` verifies the JWT signatures |
| `watson_mock.php` | watsonx Assistant v2 (sessions and messages) |
| `smtp_mock.php` | An SMTP greeter for the doctor `mail` check |
| `push_mock.php` | A web push service for the notifications tests: `/ok/*` accepts (201), `/gone/*` answers 410, `/fail/*` 500; each accepted push is logged with its headers |
| `echo.php` | Answers with the request it received (method, URI, body, `Authorization` header) to inspect outgoing calls such as `httpRequest()` |
| `application/` | QA code copied into the generated `application`: `QaController` (errors, uploads, the install module), `BookController` and `Book` (the REST API example of the wiki), `BookPageController` (a page calling a capability), a project `AIController` (a name that collides with an example controller), `Shop/OrderController` (namespaced controller), the Bookshelf capabilities of `services/Books`, the jobs of `services/QaJobs`, the capabilities of the declarative routes in `services/QaRoutes`, and the `Qa` views |
| `books.sql` | Tables of the REST API example |
| `facelogin/` | The face login example of the recipe, with the controllers `FaceLoginController` and `PasskeyController` (the recipe itself now declares these addresses with `Route::action`), the tables (`create_db.sql`) and the client app |
| `docs/` | The components example of the Vue pages of the wiki |
| `outside/` | A file outside the plugin, for the `php -l` hook test |

The mocks are plain PHP scripts served with `php -S` inside the web container (for example `php -S 127.0.0.1:8766 qa/fixtures/openai_mock.php`), and the tests point the framework to them with the base URL settings (`OPENAI_API_BASE`, `GROQ_API_BASE`, `AGENT_API_BASE`, `STRIPE_API_BASE`, `COINBASE_API_BASE`, `WATSON_URL`).
## <a name="addcheck"></a>Adding a QA check

Choose the phase by what the check needs:

+ **Framework code that needs the database or a mock** (models, payments, AI request building): add a `qa_test()` to `qa/tests/cli_tests.php`, in the right `qa_section()`. The helpers of `qa/tests/lib.php` are `qa_test($name, $fn)`, `qa_assert($condition, $message)`, `qa_equals($expected, $actual)`, `qa_contains($needle, $haystack)` and `qa_not_contains()`.
    ```php
    qa_test('endWith() compares the whole needle', function () {
        qa_assert(endWith('caligrafy.php', '.php'));
        qa_assert(!endWith('caligrafy.php', 'xphp'));
    });
    ```
+ **Behavior seen by a browser or an API client** (status codes, headers, routes): add a `qa_test()` to `qa/tests/http_tests.php`. If it needs a route, add it to the routes that `qa/run.sh` inserts into `web.php`, and its controller to `qa/fixtures/application/controllers`.
+ **Files, Caligrafer commands, scaffolds, front-end libraries, the plugin**: add an `ok`/`ko` check to `qa/tests/tooling_tests.sh`. It runs on the host and works in `qa/tmp`.
+ **doctor**: add a variant `.env` and a check to `qa/tests/doctor_tests.sh`.

Make the check fail first (break the code it protects), then make it pass. Never print a secret in a check message.
## <a name="release"></a>Release process

With [Claude Code](https://claude.com/claude-code) in the framework repository, the `caligrafy-contributor` skill (`.claude/skills/caligrafy-contributor/SKILL.md`) follows this process after every framework change, then asks whether to review the [course](https://github.com/caligrafy/caligrafy-quill-course) and whether to update and deploy caligrafy.com and Caligrafy Cloud, and ends with a report (plugin, README and wiki, course, and an inventory of every Caligrafy folder with its versions). It is for contributors only: releases leave it out (`.gitattributes`), `php caligrafer.php update` never adds it to a project, and `php caligrafer.php initialize` deletes it from a clone.

The wiki clone is `../caligrafy-quill.wiki`, next to the framework checkout (`git clone https://github.com/caligrafy/caligrafy-quill.wiki.git ../caligrafy-quill.wiki`).

1. **Claude plugin.** Update what the change touches in `claude-plugin/`: `skills/caligrafy/reference/api-reference.md` and `gotchas.md` (written by hand from the source: a new behavior goes in the API reference, a pitfall found becomes the next `G<n>`, and the range `G1-G<n>` of `skills/caligrafy/SKILL.md` follows), `ui-guidelines.md` when the look changes, every other skill and the `caligrafy-reviewer` agent, read in full against the change.
2. **README and root documents.** `README.md` (keep its banner), `ARCHITECTURE.md`, `AGENTS.md`, `CLAUDE.md`, `CONTRIBUTING.md`, `llms.txt` and `context7.json` (the index for coding agents and Context7: its rules, its links), `claude-plugin/README.md`: change what the change makes wrong or incomplete.
3. **Wiki.** Every page the change affects, read in full. A minor or major release gets a page `Release-notes:-X.Y.0.md`, linked in `_Sidebar.md`; a patch release gets a short `Release-notes:-X.Y.Z.md` too (`php caligrafer.php update` links to the release notes of the exact version it installs). The banner image is only on `Home.md`. Then refresh the plugin's mirrors of the wiki:
    ```bash
    python3 claude-plugin/scripts/sync-wiki.py ../caligrafy-quill.wiki            # rewrite the mirrors
    python3 claude-plugin/scripts/sync-wiki.py ../caligrafy-quill.wiki --check    # exit 1 when a mirror is stale
    ```
    A new wiki page needs a line in the `PAGES` table of `sync-wiki.py` and a row in the reference map of `skills/caligrafy/SKILL.md`.
    Then rebuild `llms-full.txt` (every wiki page but the release notes, in the order of the sidebar, for coding agents):
    ```bash
    php qa/build-llms-full.php ../caligrafy-quill.wiki            # rewrite it
    php qa/build-llms-full.php ../caligrafy-quill.wiki --check    # exit 1 when it is stale (the suite runs this with QA_WIKI)
    ```
4. **Plugin version.** Bump `version` in `claude-plugin/.claude-plugin/plugin.json` (minor with a framework minor, patch otherwise), add a line at the top of the changelog of `claude-plugin/README.md`, update the "Current version" line of the [Claude Code plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin) page, and validate:
    ```bash
    claude plugin validate ./claude-plugin --strict
    claude plugin validate . --strict             # the marketplace
    php caligrafer.php plugin                     # refreshes Claude Code's copy of the plugin in this checkout
    ```
    The tooling phase fails while Claude Code runs an older copy than the checkout's plugin.
5. **Framework version.** Set `Caligrafy\Framework::VERSION` in `framework/core/Framework.php` ([semantic versioning](https://semver.org): major when projects can break, minor for features, patch for fixes) and add its section at the top of `CHANGELOG.md`. The `VersionTest` unit test checks the format and the changelog.
6. **Templates changed?** When a file of `framework/settings/application` changed, rebuild the template history:
    ```bash
    php qa/build-template-history.php
    ```
    `framework/settings/template-history.json` holds the sha256 of every version each template file had in the git history (and the working tree). `php caligrafer.php upgrade` uses it to recognize untouched copies in projects that have no `application/.caligrafy-manifest.json`. The tooling phase fails when a current template version is missing from it.
7. **Run the whole suite** with the wiki clone:
    ```bash
    QA_WIKI=../caligrafy-quill.wiki ./qa/run.sh
    ```
    Before the release is tagged, the only expected failure is `caligrafer version` (it compares the version with the tag on the commit). After the tag, `sh qa/tests/tooling_tests.sh` must pass entirely.
8. **Commit, tag and push.** Commit only the files of the change (see `CONTRIBUTING.md`), then tag the release and push `master`, the tag and the wiki. Packagist picks the tag up:
    ```bash
    git tag -a v2.19.0 -m "Caligrafy Quill 2.19.0"
    git push origin master v2.19.0
    git -C ../caligrafy-quill.wiki push
    ```
9. **GitHub release.** Create it from the tag with its `CHANGELOG.md` section as its notes (it is public: the maintainer decides). Until it exists, `php caligrafer.php update` without a version does not offer the release:
    ```bash
    gh release create v2.19.0 --title "Caligrafy Quill 2.19.0" --notes-file <its CHANGELOG section> --latest
    ```
## Related pages

+ [Release notes: 2.19.0](https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.19.0)
+ [Testing your app](https://github.com/caligrafy/caligrafy-quill/wiki/Testing-Your-App): the tests of an application, not of the framework
+ [Claude Code plugin](https://github.com/caligrafy/caligrafy-quill/wiki/10.-Claude-Code-Plugin)
+ [ARCHITECTURE.md](https://github.com/caligrafy/caligrafy-quill/blob/master/ARCHITECTURE.md)

<br /><br />
>[Back to the Release notes](https://github.com/caligrafy/caligrafy-quill/wiki/Release-notes:-2.19.0)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/9.9.6-Open-Source-Agents-%28llama%2C-Mistral-etc.%29 -->

Open models (Llama, gpt-oss, Qwen, Mistral and others) run at several providers that speak the OpenAI API: Groq,
Together AI, Fireworks AI, OpenRouter, a local Ollama, or your own endpoint. `Caligrafy\Agent` talks to all of them with
the same code: only `.env` changes. You put the call in a capability, so it reaches a web page, a Vue app, the REST API
and AI agents. In the Bookshelf example, `recommend_books` suggests books to read and `describe_cover` describes an
uploaded cover image.

**Since 2.26.0** the Groq SDK is optional: run `php caligrafer.php add ai` once before using `new Agent()` with Groq (`AGENT_PROVIDER=groq`, the default). The other providers (Together, Fireworks, OpenRouter, Ollama, custom) need no SDK.
## Choosing a provider

| Provider | `AGENT_PROVIDER` | Key | Default text model | Default vision model | Audio (`transcribe`, `translate`) |
|---|---|---|---|---|---|
| [Groq](https://console.groq.com) | empty or `groq` | `GROQ_API_KEY` | `openai/gpt-oss-120b` | `qwen/qwen3.8-27b` (preview) | yes, `whisper-large-v3` |
| [Together AI](https://www.together.ai) | `together` | `TOGETHER_API_KEY` | `openai/gpt-oss-120b` | `Qwen/Qwen3.5-9B` | no |
| [Fireworks AI](https://fireworks.ai) | `fireworks` | `FIREWORKS_API_KEY` | `accounts/fireworks/models/gpt-oss-120b` | `accounts/fireworks/models/glm-5p3-flash` | no |
| [OpenRouter](https://openrouter.ai) | `openrouter` | `OPENROUTER_API_KEY` | `meta-llama/llama-3.3-70b-instruct` | `meta-llama/llama-4-maverick` | no |
| [Ollama](https://ollama.com) (your machine) | `ollama` | none | `llama3.2` | `llama3.2-vision` | no |
| any OpenAI-compatible API | `custom` | `AGENT_API_KEY` (optional) | `AGENT_MODEL` (required) | `AGENT_VISION_MODEL` | no |

**Where is Llama?** (October 2026) Groq retired its Llama chat models in August 2026. Together AI and Fireworks AI serve
Llama only on dedicated or on-demand deployments, so their defaults are `gpt-oss-120b`. For Llama pay-per-token choose
**OpenRouter**; for free Llama on your own computer choose **Ollama**. Models change often: `docker compose exec dev-box php caligrafer.php doctor
--only agent` lists those of your key.

Costs: Groq has a free developer tier with rate limits; Together, Fireworks and OpenRouter bill per token (OpenRouter
from prepaid credits; models whose id ends with `:free` cost nothing but have daily limits); Ollama is free and as fast
as your computer. Check each provider's pricing page.
## With Claude

```text
/caligrafy-quill:new-capability recommend_books ai:use read-only
Recommend three books from the books a reader liked, with an open model through Caligrafy\Agent (Llama on OpenRouter).
```

Claude writes the capability in `application/services/`, sets the provider settings it needs in `.env` (names only:
you paste the key), and runs `docker compose exec dev-box php caligrafer.php doctor --only agent`. For a chat app in Vue,
`/caligrafy-quill:new-app app chat` follows the plugin's AI chat recipe; it asks which provider when you say "Llama".

**Check**
- The key of the chosen provider is in `.env`, nowhere else; `doctor --only agent` shows the provider, the key accepted
  and the models available.
- `new Agent()` sits in a `try`: a missing key or an unknown provider becomes a readable refusal.
- `api_success` is checked: provider errors come back as its `response` text.
- A capability that receives an image reads a saved upload, never a URL sent by the caller.
## By hand

The project has sign-in, `Route::capabilities('/capabilities')` and `Route::mcp('/mcp')` (see the
[Quickstart](https://github.com/caligrafy/caligrafy-quill/wiki/Quickstart)). Without Docker (Composer with MAMP, XAMPP or LAMP), run the same commands without `docker compose exec dev-box` and open your own address.

### Step 1: Choose the provider in `.env`

OpenRouter (Llama in the cloud), with a key from [openrouter.ai/settings/keys](https://openrouter.ai/settings/keys):

```text
AGENT_PROVIDER=openrouter
OPENROUTER_API_KEY=sk-or-...
AGENT_MODEL=
AGENT_VISION_MODEL=
```

Or Ollama on your computer (see [Running Llama locally with Ollama](#ollama)):

```text
AGENT_PROVIDER=ollama
AGENT_API_BASE=
```

Or Groq (the default when `AGENT_PROVIDER` is empty), with a key from [console.groq.com/keys](https://console.groq.com/keys):

```text
AGENT_PROVIDER=
GROQ_API_KEY=gsk_...
```

Run:

```bash
docker compose exec dev-box php caligrafer.php doctor --only agent
```

Expected, for example:

```text
 Agent provider
  OK    AGENT_PROVIDER: openrouter (OpenRouter), https://openrouter.ai/api/v1
  OK    OpenRouter: key accepted, ... models available
  OK    AGENT_MODEL: meta-llama/llama-3.3-70b-instruct is available
  OK    AGENT_VISION_MODEL: meta-llama/llama-4-maverick is available
```

With Groq, the Groq check runs instead and warns about retired models.

### Step 2: The capability

```bash
docker compose exec dev-box php caligrafer.php service Bookshelf/RecommendBooks --scope ai:use --read-only
```

Replace **`application/services/Bookshelf/RecommendBooks.php`** with:

```php
<?php
/**
 * RecommendBooks: book ideas from an open model (Llama, gpt-oss, Qwen...) through the Agent class
 */

use Caligrafy\Agent;
use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;
use Caligrafy\ServiceError;

#[Capability(
    name: 'recommend_books',
    description: 'Recommends three books for a reader from the books they liked. Returns {model, recommendations}.',
    scope: 'ai:use',
    readOnly: true
)]
class RecommendBooks extends Service
{
    public $rules = array(
        'liked' => 'required|max_len,1000',
    );

    public $filters = array(
        'liked' => 'trim',
    );

    public $descriptions = array(
        'liked' => 'Books the reader liked, for example "Kindred, The Dispossessed"',
    );

    public function handle(array $input, Context $context)
    {
        try {
            $agent = new Agent();   // provider, key and models come from .env (AGENT_PROVIDER...)
        } catch (Exception $e) {
            throw ServiceError::conflict('The AI provider is not set up: ' . $e->getMessage());
        }

        $result = $agent->delegate(messages: array(
            array('role' => 'system', 'content' => 'You are a librarian. Answer with a list of three books, one per line: title, author, and why in one sentence.'),
            array('role' => 'user', 'content' => 'I liked: ' . $input['liked']),
        ));
        if (empty($result['api_success'])) {
            throw ServiceError::conflict((string) $result['response']);   // the provider's message
        }

        return array('model' => $agent->model(), 'recommendations' => $result['response']);
    }
}
```

What it does:
+ `new Agent()` reads the provider, its key and its models from `.env`. It throws when the provider is unknown, its key
  is missing, or `custom` has no `AGENT_API_BASE`: the capability turns that into a `conflict` refusal (409) with the
  reason. (The agent is created in `handle()`, not through the constructor, so that this refusal is readable.)
+ `delegate(messages: ...)` uses the provider's default model and returns `['api_success' => true, 'response' => text]`,
  or `api_success` false with the provider's error (`OpenRouter error 401: ...`, *is Ollama running?*).

```bash
docker compose exec dev-box php caligrafer.php call recommend_books liked="Kindred, The Dispossessed"
```

Expected (the text varies):

```json
{
    "data": {
        "model": "meta-llama/llama-3.3-70b-instruct",
        "recommendations": "1. Parable of the Sower, Octavia E. Butler: ..."
    }
}
```

Without a key for the provider: `{"error": {"code": "conflict", "message": "The AI provider is not set up: The OpenRouter
API key is not set: add OPENROUTER_API_KEY=<your key> (or AGENT_API_KEY) to .env - create one on https://openrouter.ai/settings/keys"}}`.

The same capability is now `POST /capabilities/recommend_books` for REST and the JS client (`recommendBooks({ liked })`),
and the tool `recommend_books` for agents on `/mcp`. A page shows it with a form, as `write_blurb` does on the
[OpenAI page](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.4-OpenAI:-ChatGPT,-GPTs,-DALL.E):

```php
Route::form('/recommend', 'recommend_books', ['success' => '/recommend', 'back' => '/recommend', 'flash' => '{recommendations}']);
```

### Step 3: Describe an image (vision)

```bash
docker compose exec dev-box php caligrafer.php service Bookshelf/DescribeCover --scope ai:use --read-only
```

Replace **`application/services/Bookshelf/DescribeCover.php`** with:

```php
<?php
/**
 * DescribeCover: describes an uploaded cover image with the vision model of the provider
 */

use Caligrafy\Agent;
use Caligrafy\Capability;
use Caligrafy\Context;
use Caligrafy\Service;
use Caligrafy\ServiceError;

#[Capability(
    name: 'describe_cover',
    description: 'Describes a book cover image in two sentences. Returns {description}.',
    scope: 'ai:use',
    readOnly: true,
    mcp: false
)]
class DescribeCover extends Service
{
    public $rules = array(
        'cover' => 'required|file|extension,png;jpg;jpeg;webp|max_size,4mb',
    );

    public $descriptions = array(
        'cover' => 'The cover image (PNG, JPEG or WebP, 4 MB at most)',
    );

    public function handle(array $input, Context $context)
    {
        // the page or REST saved the upload in public/uploads and sent its URL: read that file, never a URL
        $file = UPLOAD_PATH . basename((string) parse_url($input['cover'], PHP_URL_PATH));
        if (!is_file($file)) {
            throw ServiceError::invalid(array('cover' => 'Send the cover as an uploaded file'));
        }

        try {
            $agent = new Agent();
            $result = $agent->visualize($file, 'Describe this book cover in two sentences.');
        } catch (Exception $e) {
            throw ServiceError::conflict('The AI provider is not set up: ' . $e->getMessage());
        } finally {
            deleteFile($input['cover']);   // the cover was only needed for this answer
        }
        if (empty($result['api_success'])) {
            throw ServiceError::conflict((string) $result['response']);
        }

        return array('description' => $result['response']);
    }
}
```

+ The `file` rule makes web forms and REST save the upload in `public/uploads` under a random name and give `handle()`
  its URL. The capability reads that saved file by name, so a URL sent by a caller never makes your server fetch
  anything; `mcp: false` keeps it away from agents, which cannot send files.
+ `visualize($file, $prompt)` sends the image with the provider's vision model. The file is deleted afterwards.

Send a cover with REST (a token with `ai:use`, see
[Caligrafer: token](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#token)):

```bash
curl -H "Accept: application/json" -H "Authorization: Bearer cq_..." -F cover=@cover.png \
  http://localhost:8080/capabilities/describe_cover
```

Expected: `200` and `{"data":{"description":"..."}}`. Sent as JSON text instead of a file, or with no cover, it is refused:
`422`, *The Cover field needs a file* (2.19.1: `required` on a file input now holds on every channel). A form posts it the same way (`enctype='multipart/form-data'`, see
[file inputs](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#files)).

**Check**
- `docker compose exec dev-box php caligrafer.php doctor --only agent` is all OK.
- `docker compose exec dev-box php caligrafer.php call recommend_books liked=Kindred` answers `data`; with the key removed it answers a `conflict`
  that names the missing setting.
- `public/uploads` holds no cover after a `describe_cover` call.

<a name="ollama"></a>
### Running Llama locally with Ollama

1. Install Ollama from [ollama.com/download](https://ollama.com/download) (macOS, Windows) or with
   `curl -fsSL https://ollama.com/install.sh | sh` (macOS, Linux).
2. Pull the models: `ollama pull llama3.2` (3B, about 2 GB) and, for images, `ollama pull llama3.2-vision` (11B, about
   8 GB). Bigger ones (`llama3.3` 70B, `llama4`) need a strong machine: see the [Ollama library](https://ollama.com/library).
3. Check that it runs: `ollama list` shows the models and `curl http://localhost:11434/v1/models` answers. The Ollama
   app starts the server; otherwise run `ollama serve`.
4. Set `AGENT_PROVIDER=ollama` in `.env`. When PHP runs in Docker, `localhost` is the container: set
   `AGENT_API_BASE=http://host.docker.internal:11434/v1`. Docker Desktop resolves `host.docker.internal`; on Linux add
   `extra_hosts: ["host.docker.internal:host-gateway"]` to the `dev-box` service of `docker-compose.yaml` and start
   Ollama with `OLLAMA_HOST=0.0.0.0`.
5. `docker compose exec dev-box php caligrafer.php doctor --only agent` (without Docker: `php caligrafer.php doctor --only agent`)
   confirms that the server answers and the models are pulled. A model without a tag is `:latest`.
## Reference

### `new Agent($apiKey = "", $provider = "", $baseUrl = "")`

Empty arguments come from `.env`. Each setting is found in this order:

| Setting | Order |
|---|---|
| provider | the argument, `AGENT_PROVIDER`, else `groq` |
| key | the argument, the provider's key (`GROQ_API_KEY`, `TOGETHER_API_KEY`, `FIREWORKS_API_KEY`, `OPENROUTER_API_KEY`), then `AGENT_API_KEY`; never another provider's key. Ollama needs none |
| endpoint | the argument, `AGENT_API_BASE`, `GROQ_API_BASE` (Groq only), then the provider's default |
| text model | `AGENT_MODEL`, `GROQ_MODEL` (Groq only), then the default of the table above |
| vision model | `AGENT_VISION_MODEL`, `GROQ_VISION_MODEL` (Groq only), then the default |

Examples: `new Agent(provider: 'ollama')`, `new Agent('key', 'custom', 'https://llm.example.com/v1')`. Groq goes through
the groq-php library; the others through a built-in HTTP client (120 s timeout; OpenRouter also gets `HTTP-Referer:
APP_URL` and `X-Title: APP_NAME`).

### Methods

| Method | Returns |
|---|---|
| `delegate($model = "", $messages = array(), $response_format = array(), $stream = false, $tool_choice = "", $tools = array())` | `['api_success' => bool, 'response' => text or error]`; `$model` empty = `model()`; `$response_format` e.g. `['type' => 'json_object']`; `$stream` true reads the streamed answer and returns it as one text (other providers than Groq); `$tools`, `$tool_choice` in OpenAI's format |
| `visualize($file = "", $prompt = "Describe this image", $model = "")` | same shape; `$model` empty = `visionModel()`. Groq: a file of 4 MB at most, or a URL. Others: a local image file (sent as base64, 20 MB at most) or a public http(s) URL passed to the provider |
| `transcribe($file = "", $prompt = "", $model = GROQ_TRANSCRIPTION_MODEL, $language = "en", $response_format = "json")` | Groq's answer as a JSON string; Groq only (others throw *needs Groq*) |
| `translate($file = "", $prompt = "", $model = GROQ_TRANSCRIPTION_MODEL, $response_format = "json")` | audio to English text, JSON string; Groq only |
| `models()` | `['api_success' => true, 'response' => sorted model ids]` (Ollama: the pulled models), or `false` and the error |
| `configure($parameters = array())` | adds parameters (`temperature`, `max_tokens`...) to every `delegate()` and `visualize()`; returns the agent |
| `provider()`, `model()`, `visionModel()` | the provider in use and its default models |
| `Agent::settings()`, `Agent::modelIds($json)`, `Agent::PROVIDERS` | the resolved settings (doctor uses them), model ids of a `/models` answer, the providers table |

For audio next to another provider, keep `GROQ_API_KEY` and use `new Agent(provider: 'groq')`.

### Constants (Groq)

`GROQ_DEFAULT_MODEL` (`openai/gpt-oss-120b`, or `GROQ_MODEL`), `GROQ_SMALL_MODEL` (`openai/gpt-oss-20b`),
`GROQ_DEFAULT_VISION_MODEL` (`qwen/qwen3.8-27b`, or `GROQ_VISION_MODEL`), `GROQ_TRANSCRIPTION_MODEL` (`whisper-large-v3`).
In code that may run on another provider, use `$agent->model()` and `$agent->visionModel()` instead.

### `.env` for every provider

```text
AGENT_PROVIDER=together
TOGETHER_API_KEY=...          # https://api.together.ai/settings/api-keys

AGENT_PROVIDER=fireworks
FIREWORKS_API_KEY=...         # https://fireworks.ai/account/api-keys

AGENT_PROVIDER=custom         # vLLM, LM Studio, a gateway...
AGENT_API_BASE=https://llm.example.com/v1
AGENT_API_KEY=...             # only when the endpoint needs one
AGENT_MODEL=<model id>
```

A Llama deployment on Together or Fireworks: put the model id of your deployment in `AGENT_MODEL`.

<a name="migrating"></a>
### Migrating from the Groq Llama models

Groq retired these models; requests with them fail with *model decommissioned* or *does not exist*.

| Groq model (retired) | The same Llama elsewhere | Replacement on Groq |
|---|---|---|
| `llama-3.3-70b-versatile` | OpenRouter `meta-llama/llama-3.3-70b-instruct`, Ollama `llama3.3` | `openai/gpt-oss-120b` |
| `llama-3.1-8b-instant` | OpenRouter `meta-llama/llama-3.1-8b-instruct`, Ollama `llama3.1` | `openai/gpt-oss-20b` |
| `meta-llama/llama-4-scout-17b-16e-instruct` | OpenRouter `meta-llama/llama-4-scout` | `openai/gpt-oss-120b`, `qwen/qwen3.8-27b` (vision) |
| `meta-llama/llama-4-maverick-17b-128e-instruct` | OpenRouter `meta-llama/llama-4-maverick`, Ollama `llama4` | `openai/gpt-oss-120b` |
| `llama-3.2-11b-vision-preview`, `llama-3.2-90b-vision-preview` | Ollama `llama3.2-vision` | `qwen/qwen3.8-27b` |
| `llama3-70b-8192`, `llama3-8b-8192` | OpenRouter `meta-llama/llama-3.3-70b-instruct` / `meta-llama/llama-3.1-8b-instruct` | `openai/gpt-oss-120b` / `openai/gpt-oss-20b` |

To keep Llama: set `AGENT_PROVIDER=openrouter` (or `ollama`), replace the Groq ids in your code or `GROQ_MODEL` with the
middle column (or remove them to use the defaults), then run `docker compose exec dev-box php caligrafer.php doctor --only agent`.
## Other ways

**Streaming the answer.** A capability serves every channel and is the way to write the agent. To stream the answer word by
word to the browser, serve a web-only capability with [`Route::action`](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes#action): it sets its header, prints and
flushes each word, then returns `Web::text('')`. Controllers in older code return `api($agent->delegate(...))`.
## Common mistakes

+ **Expecting Llama on Groq.** It is gone: use OpenRouter or Ollama.
+ **Switching `AGENT_PROVIDER` without that provider's key.** The key of another provider is never used: `new Agent()`
  throws. Run `doctor --only agent`.
+ **`localhost` from Docker.** PHP in the container does not reach Ollama on your computer at `localhost`: use
  `AGENT_API_BASE=http://host.docker.internal:11434/v1`.
+ **Passing a URL from the client to `visualize()`.** Your server or the provider would fetch whatever it points to.
  Save the upload (the `file` rule) and pass the saved file.
+ **`transcribe()` on another provider.** Audio is Groq only.
+ **`GROQ_DEFAULT_MODEL` in code that runs on OpenRouter.** Use `$agent->model()`.
## Related pages

+ [OpenAI: ChatGPT, GPTs, DALL.E](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.4-OpenAI:-ChatGPT,-GPTs,-DALL.E): the page with the form and the test, step by step
+ [OpenAI: Assistants](https://github.com/caligrafy/caligrafy-quill/wiki/9.9.5-Open-AI:-Assistants)
+ [Build once: services, capabilities and MCP](https://github.com/caligrafy/caligrafy-quill/wiki/11.-Build-Once:-Services,-Capabilities-and-MCP)
+ [Declarative routes](https://github.com/caligrafy/caligrafy-quill/wiki/Declarative-Routes): forms and file inputs
+ [Caligrafer: doctor](https://github.com/caligrafy/caligrafy-quill/wiki/Caligrafer#doctor)


---

<!-- Source: https://github.com/caligrafy/caligrafy-quill/wiki/API-Database -->

<!-- Generated by qa/build-api-reference.php from the framework source: do not edit by hand. -->
# Caligrafy\Database

> Caligrafy Quill 2.26.0. Generated from the source by `php qa/build-api-reference.php`; the guides explain how to use these classes, this reference says exactly what each public method takes and returns. Back to the [API reference](https://github.com/caligrafy/caligrafy-quill/wiki/API-Reference).

Part of [Data](https://github.com/caligrafy/caligrafy-quill/wiki/API-Data).

<a name="database"></a>
```php
namespace Caligrafy;

class Database extends \stdClass
```

Source: [framework/database/Database.php:19](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L19)

The Database class handles all database connections and global functions that interface directly with the database

## Methods

+ [`Database::connect()`](#database-connect)
+ [`Database::persistent()`](#database-persistent)
+ [`Database::reset()`](#database-reset)
+ [`Database::alignTimeZone()`](#database-aligntimezone)
+ [`Database::dsn()`](#database-dsn)
+ [`Database::execute()`](#database-execute)
+ [`Database::render()`](#database-render)
+ [`Database::toArray()`](#database-toarray)
+ [`Database::is_Json()`](#database-is-json)
+ [`Database::connection()`](#database-connection)
+ [`Database::endRequest()`](#database-endrequest)
+ [`Database::useConnection()`](#database-useconnection)
+ [`Database::table()`](#database-table)
+ [`Database::transaction()`](#database-transaction)
+ [`Database::rowCount()`](#database-rowcount)
+ [`Database::lastInsertId()`](#database-lastinsertid)

<a name="database-connect"></a>
### `Database::connect()`

```php
public static function connect()
```

Connects to the database

**Returns** `the`: database connection

Source: [framework/database/Database.php:39](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L39)

<a name="database-persistent"></a>
### `Database::persistent()`

```php
public static function persistent($adapter)
```

Whether this process keeps its database connection between requests (2.26.0): DB_PERSISTENT, true by default for
MySQL and PostgreSQL in a web server; never on the command line (tests, migrations, the queue: each run is fresh),
never for SQLite. DB_PERSISTENT=false connects on every request, as before 2.26.0.

**Parameters**

+ `$adapter`

Source: [framework/database/Database.php:62](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L62)

<a name="database-reset"></a>
### `Database::reset()`

```php
public static function reset($connection)
```

A reused connection starts clean: a transaction the previous request left open is rolled back (PHP rolls it back
at the end of a request too; this is the second lock), and the session time zone is set again by alignTimeZone.
PDO checks that a reused connection is alive and opens a new one if the database dropped it.

**Parameters**

+ `$connection`

Source: [framework/database/Database.php:79](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L79)

<a name="database-aligntimezone"></a>
### `Database::alignTimeZone()`

```php
public static function alignTimeZone($connection, $adapter)
```

MySQL session time zone = PHP's (SERVER_TIMEZONE), so that NOW(), CURRENT_TIMESTAMP columns and the times PHP
writes (the audit log) use the same clock. DB_TIMEZONE=server keeps the database server's own time zone.

**Parameters**

+ `$connection`
+ `$adapter`

Source: [framework/database/Database.php:95](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L95)

<a name="database-dsn"></a>
### `Database::dsn()`

```php
public static function dsn($adapter, $host, $dbName, $port = null)
```

Builds the PDO DSN from the DB_* settings
DB_PORT is added unless DB_HOST already carries a ';port=' (older workaround)

**Parameters**

+ `$adapter`
+ `$host`
+ `$dbName`
+ `$port`, default `null`

**Returns** `string`: the DSN

Source: [framework/database/Database.php:112](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L112)

<a name="database-execute"></a>
### `Database::execute()`

```php
public static function execute($query, $args = array())
```

Executes PDO Query

**Parameters**

+ `$query` `string`: defines the query to be executed
+ `$args` `array`, default `array()`: defines the argument that need to be bound to the query

**Returns** `rendered`: result in array or json format

Source: [framework/database/Database.php:131](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L131)

<a name="database-render"></a>
### `Database::render()`

```php
public static function render($result)
```

Result rendered

**Parameters**

+ `$result` `array`: defines the result coming from the database in an array format

**Returns** `rendered`: result in array or json format depending on the setting

Source: [framework/database/Database.php:161](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L161)

<a name="database-toarray"></a>
### `Database::toArray()`

```php
public static function toArray($result)
```

Forces the result to an array

**Parameters**

+ `$result` `array`: defines the result coming in either a json or array format

**Returns** `array`: $result the result rendered as an array

Source: [framework/database/Database.php:179](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L179)

<a name="database-is-json"></a>
### `Database::is_Json()`

```php
public static function is_Json($string)
```

Checks if a string i a JSON

**Parameters**

+ `$string` `string`: defines the string to be checked

**Returns** `boolean`: if the string is a JSON

Source: [framework/database/Database.php:197](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L197)

<a name="database-connection"></a>
### `Database::connection()`

```php
public static function connection()
```

The PDO connection, connecting on first use (null when DB_ACTIVATE is not true); tests run in its transactions

Source: [framework/database/Database.php:206](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L206)

<a name="database-endrequest"></a>
### `Database::endRequest()`

```php
public static function endRequest()
```

The end of a request in a process that serves many (2.26.0, the async server): a transaction left open is rolled
back, the counters forgotten; the connection stays open for the next request

Source: [framework/database/Database.php:230](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L230)

<a name="database-useconnection"></a>
### `Database::useConnection()`

```php
public static function useConnection($connection = null)
```

Uses this PDO connection (a test's in-memory SQLite, a worker's own connection); null connects again on next use

**Parameters**

+ `$connection`, default `null`

Source: [framework/database/Database.php:242](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L242)

<a name="database-table"></a>
### `Database::table()`

```php
public static function table($table)
```

A query builder on a table: Database::table('books')-&gt;where('price', '&lt;', 20)-&gt;get()

**Parameters**

+ `$table` `string`: the table (letters, digits, _)

**Returns** `Query`

Source: [framework/database/Database.php:253](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L253)

<a name="database-transaction"></a>
### `Database::transaction()`

```php
public static function transaction(callable $callback)
```

Runs $callback in a transaction: committed when it returns, rolled back when it throws (the exception is
thrown again). A transaction inside another one (or inside a test's transaction) just runs in the outer one.

**Parameters**

+ `$callback` `callable`

**Returns** `mixed`: what $callback returns

Source: [framework/database/Database.php:263](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L263)

<a name="database-rowcount"></a>
### `Database::rowCount()`

```php
public static function rowCount()
```

The number of rows the last INSERT, UPDATE or DELETE changed

Source: [framework/database/Database.php:291](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L291)

<a name="database-lastinsertid"></a>
### `Database::lastInsertId()`

```php
public static function lastInsertId()
```

Gets Last Inserted Id

**Returns** `int`: Last Inserted Id

Source: [framework/database/Database.php:302](https://github.com/caligrafy/caligrafy-quill/blob/v2.26.0/framework/database/Database.php#L302)